Professional Documents
Culture Documents
Featured Articles:
Hello World Advanced calculator Create controls at runtime Check for Anagrams Indexer Basics Write to Windows Registry Decimal to Binary Caller Information Basics Reverse individual words Named Arguments/Parameters Optional Arguments/Parameters Transpose a Matrix Fibonacci series program Get Date Difference Obtain Local Host IP Change monitor state Linear & Binary search Strings selection property Matrix Multiplication DGV Filter & Expressions Stream Writer Basics Send an Email Databinding Tutorial Create a Right Click Menu Custom user Settings Polymorphism Basics Inheritance Basics Random generator class Auto-complete Feature Database Insert & Retrieve Fetch data from table Drawing with mouse
http://www.code-kings.blogspot.com/
Page 1
using System; namespace Hello_World { public partial class FrmHelloWorld : Form { public FrmHelloWorld() { InitializeComponent(); } private void timer1_Tick(object sender, EventArgs e) { lblWorld.visible = false; lblHello.Visible = true; timer1.Enabled = false; timer2.Enabled = true; }
http://www.code-kings.blogspot.com/
Page 2
private void timer2_Tick(object sender, EventArgs e) { lblHello.Visible = false; lblWorld.Visible = true; timer2.Enabled = false; timer1.Enabled = true; } private void cmdClickHere_Click(object sender, EventArgs e) { if (cmdClickHere.Text = "Click Here !") { timer1.Enabled = true; cmdClickHere.Text = "STOP !"; } else if (cmdClickHere.Text = "STOP !") { timer1.Enabled = false; timer2.Enabled = false; cmdClickHere.Text = "Click Here !"; } } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 3
An Advanced Calculator in C#
The .Net Framework provides a Math class with a loads of mathematical functions like Sin, Cos, Tan, ASin, ACos, ATan, Floor, Ceiling, Power, Log, Ln etc. We can easily use them by simply referring to the Math functions. These Math class functions take suitable parameters and return appropriate datatypes which can be easily changed to Strings or Doubles. The conversion here done is with the help of Convert class.
This is just another basic piece of code which illustrates a different approach to the simple calculator which we use daily. The calculator is designed to do 7 basic calculations like +,,*,/,sin,cos,tan. Of course there is no limit to the ways in which we can combine these and create even more complex formulas. The calculator stores different calculations in different textboxes, also showing the operand/s. This is simply achieved by concatenating the operands retrieved from textboxes with the appropriate operation sign in between and then appending the calculated result in the end after an = sign. A word of caution : C# asks programmers to be strict with the datatypes so we must convert and match existing datatypes to perform operations especially mathematical. In other words we cannot apply the * operation on two strings , instead we have to convert the strings to integers and then apply the operation. This is simply achieved by using the function Convert.ToInt32() which converts its
http://www.code-kings.blogspot.com/ Page 4
parameter into a 32 bit integer value(using 16 instead of 32 would convert it to a 16 bit integer value which also has a smaller range as compared to 32 bit).
using System; namespace Advanced_Calculator { public partial class Form1 : Form { public Form1(){InitializeComponent();} private void Addition_Click(object sender, EventArgs e) { txtAddition.Text = txtX.Text + " + " + txtY.Text + " = " + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text))+(Convert.ToInt3 2(txtY.Text)))); } private void Subtraction_Click(object sender, EventArgs e) { txtSubtraction.Text = txtX.Text + " - " + txtY.Text + " = " + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text)) (Convert.ToInt32(txtY.Text)))); } private void Multiplication_Click(object sender, EventArgs e) { txtMultiplication.Text = txtX.Text + " * " + txtY.Text + " = " + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text)) * (Convert.ToInt32(txtY.Text)))); } private void Division_Click(object sender, EventArgs e) { txtDivision.Text = txtX.Text + " / " + txtY.Text + " = " + Convert.ToString(Convert.ToInt32((Convert.ToInt32(txtX.Text)) / (Convert.ToInt32(txtY.Text)))); } private void SinX_Click(object sender, EventArgs e) { txtSinX.Text = " Sin " +txtX.Text + " = " + Convert.ToString(Math.Sin(Convert.ToDouble(txtX.Text))); } private void CosX_Click(object sender, EventArgs e) { txtCosX.Text = " Cos " + txtX.Text + " = " + Convert.ToString(Math.Cos(Convert.ToDouble(txtX.Text))); }
http://www.code-kings.blogspot.com/
Page 5
private void TanX_Click(object sender, EventArgs e) { txtTanX.Text = " Tan " + txtX.Text + " = " + Convert.ToString(Math.Tan(Convert.ToDouble(txtX.Text))); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 6
Creating controls at runtime can be very useful if you have some conditions that you might want to satisfy before displaying a set of controls. You might want to display different controls for different situations. CSharp provides an easy method to create them. If you look carefully in the Designer of any form, you will find codes that initiate the creation of controls. You will see some properties set, leaving other properties default. And this is exactly what we are doing here. We are writing code behinf the Fom that creates the controls with some properties set by ourselves & others are simply set to their default value by the Compiler. The main steps to draw controls are summarized below:
Create/Define the control or Array of controls Set the properties of the control or individual controls in case of Arrays Add the control/s to the form or other parent containers such as Panels Call the Show() method to display the control Thats it!
http://www.code-kings.blogspot.com/
Page 7
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 8
namespace Anagram_Test { class ClassCheckAnagram { public int check_anagram(char[] a, char[] b) { Int16[] first = new Int16[26]; Int16[] second = new Int16[26]; int c = 0; for (c = 0; c < a.Length; c++) { first[a[c] - 'a']++; } c = 0; for (c=0; c<b.Length; c++) { second[b[c] - 'a']++; } for (c = 0; c < 26; c++) { if (first[c] != second[c]) return 0; } return 1; } } }
http://www.code-kings.blogspot.com/
Page 9
using System; namespace Anagram_Test { class Program { static void Main(string[] args) { ClassCheckAnagram cca = new ClassCheckAnagram(); Console.WriteLine("Enter first string\n"); string aa = Console.ReadLine(); char[] a = aa.ToCharArray(); Console.WriteLine("\nEnter second string\n"); string bb = Console.ReadLine(); char[] b = bb.ToCharArray(); int flag = cca.check_anagram(a, b); if (flag == 1) Console.WriteLine("\nThey are anagrams.\n"); else Console.WriteLine("\nThey are not anagrams.\n"); Console.ReadKey(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 10
Using Indexers in C# 5
Indexers are elements in a C# program that allow a Class to behave as an Array. You would be able to use the entire class as an array. In this array you can store any type of variables. The variables are stored at a separate location but addressed by the class name itself. Creating indexers for Integers, Strings, Boolean etc. would be a feasible idea. These indexers would effectively act on objects of the class. Lets suppose you have created a class indexer that stores the roll number of a student in a class. Further, lets suppose that you have created an object of this class named obj1. When you say obj1[0], you are referring to the first student on roll. Likewise obj1[1] refers to the 2nd student on roll. Therefore the object takes indexed values to refer to the Integer variable that is privately or publicly stored in the class. Suppose you did not have this facility then you would probably refer in this way:
obj1.RollNumberVariable[0] obj1.RollNumberVariable[1].
where RollNumberVariable would be the Integer variable. Now that you have learnt how to index your class & learnt to skip using variable names again and again, you can effectively skip the variable name RollNumberVariable by indexing the same. Indexers are created by declaring their access specifier and WITHOUT a return type. The type of variable that is stored in the Indexer is specified in the parameter type following the name of the Indexer. Below is the program that shows how to declare and use Indexers in a C# Console environment:
using System; namespace Indexers_Example { class Indexers { private Int16[] RollNumberVariable; public Indexers(Int16 size) { RollNumberVariable = new Int16[size]; for (int i = 0; i < size; i++) { RollNumberVariable[i] = 0; } }
http://www.code-kings.blogspot.com/
Page 11
public Int16 this[int pos] { get { return RollNumberVariable[pos]; } set { RollNumberVariable[pos] = value; } } } } using System; namespace Indexers_Example { class Program { static void Main(string[] args) { Int16 size = 5; Indexers obj1 = new Indexers(size); for (int i = 0; i < size; i++) { obj1[i] = (short)i; } Console.WriteLine("\nIndexer Output\n"); for (int i = 0; i < size; i++) { Console.WriteLine("Next Roll No: " + obj1[i]); } Console.Read(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 12
The Keys at the parent level are HKEY_CLASSES_ROOT, HKEY_CURRENT_USER etc. When we refer to these keys in our C# program code, we omit the HKEY & the underscores. So, to refer to the HKEY_CURRENT_USER, we use simply CurrentUser as the reference. Well, this reference is available from the Microsoft.Win32.Registry class. This Registry class is available through the reference:
using Microsoft.Win32;
We use this reference to create a Key object. An example of a Key object would be:
Microsoft.Win32.RegistryKey key;
Now this key object can be set to create a Subkey in the parent folder. In the example below, we have used the CurrentUser as the parent folder:
key = Microsoft.Win32.Registry.ClassesRoot.CreateSubKey("CSharp_Website");
Next we can set the Value of this Field using the SetValue() funtion. See below:
key.SetValue("Really", "Yes!");
http://www.code-kings.blogspot.com/
Page 13
As you will see in the picture below, you can select different parent folders(such as ClassesRoot, CurrentConfig etc.) to create and set different key values:
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 14
using System; namespace convert_decimal_to_binary { class Program { static void Main(string[] args) { int n, c, k; Console.WriteLine("Enter an integer in Decimal number system\n"); n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\nBinary Equivalent is:\n"); for (c = 31; c >= 0; c--) { k = n >> c; if (Convert.ToBoolean(k & 1)) Console.Write("1"); else Console.Write("0"); } Console.ReadKey(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 15
Caller Information in C#
Caller Information is a new concept introduced in C# 5. It is aimed at providing useful information about where a function was called. It gives information such as:
Full path of the source file that contains the caller. This is the file path at compile time. Line number in the source file at which the method is called. Method or property name of the caller.
We specify the following(as optional parameters) attributes in the function definition respectively:
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/ Page 16
using System; namespace Reverse_String_Test { class Program { public static string reverseIt(string strSource) { string[] arySource = strSource.Split(new char[] { ' ' }); string strReverse = string.Empty; for (int i = arySource.Length - 1; i >= 0; i--) { strReverse = strReverse + " " + arySource[i]; } Console.WriteLine("Original String: \n\n" + strSource); Console.WriteLine("\n\nReversed String: \n\n" + strReverse); return strReverse; }
http://www.code-kings.blogspot.com/
Page 17
static void Main(string[] args) { reverseIt(" I Am In Love With www.code-kings.blogspot.com.com"); Console.WriteLine("\nPress any key to continue...."); Console.ReadKey(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 18
Named Arguments/Parameters in C#
Named Arguments are an alternative way for specifing of parameter values in function calls. They work so that the position of the parameters would not pose problems. Therefore it reduces the headache of remembering the positions of all parameters for a function. They work in a very simple way. When we call a function, we would write the name of the parameter before specifiying a value for the parameter. In this way, the position of the argument will not matter as the compiler would tally the name of the parameter against the parameter value. Consider a function definition below: static int remainder(int dividend, int divisor) { return( dividend % divisor ); } Now we call this function using two methods with a Named Parameter:
Note that the position of the arguments have been interchanged, both the above methods will produce the same output i.e. they would set the value of a as 0(which is the remainder when dividing 10 by 5).
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 19
Optional Arguments/Parameters in C#
This article will show you what is meant by Optional Arguments/Parameters in C# 5.0. Optional Arguments are mostly necessary when you specify functions that have a large number of arguments. Optional Arguments are purely optional i.e. even if you do not specify them, its perfectly OK. But it doesn't mean that they have not taken a value. In fact we specify some default values that the Optional Parameters take when values are not supplied in the function call.
The values that we supply in the function Definition are some constants. These are the values that are to be used in case no value is supplied in the function call. These values are specified by typing in variable expressions instead of just the declaration of variables. For example, we would write
static void Func(Str = "Default Value")
instead of static void Func(int Str) If you didn't know this technique, you were probably using Function Overloading, but that technique requires multiple declaration of the same function. Using this technique you can define the function only once and have the functionality of multiple function declarations. When using this technique it is best that you have declared optional & required parameters both. i.e. you can specify both types of parameters in your function declaration to get the most out of this technique. An example of a function that uses both types of parameters is shown below: static void Func(String Name, int Age, String Address = "N/A") In the example above, Name & Age are required parameters. The string Address is optional, if not specified, then it would take the value "N/A" meaning that the Address is not available. For the above example, you could have two types of function calls:
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 20
Transpose a Matrix
This program illustrates how to find the transpose of a given matrix. Check code below for details.
using System; using System.Text; using System.Threading.Tasks; namespace Transpose_a_Matrix { class Program { static void Main(string[] args) { int m, n, c, d; int[,] matrix = new int[10, 10]; int[,] transpose = new int[10, 10]; Console.WriteLine("Enter the number of rows and columns of matrix "); m = Convert.ToInt16(Console.ReadLine()); n = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter the elements of matrix \n"); for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { matrix[c, d] = Convert.ToInt16(Console.ReadLine()); } } for (c = 0; c < m; c++) { for (d = 0; d < n; d++) { transpose[d, c] = matrix[c, d]; } }
http://www.code-kings.blogspot.com/
Page 21
Console.WriteLine("Transpose of entered matrix"); for (c = 0; c < n; c++) { for (d = 0; d < m; d++) { Console.Write(" " + transpose[c, d]); } Console.WriteLine(); } Console.ReadKey(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 22
Fibonacci Series
Fibonacci series is a series of numbers where the next number is the sum of the previous two numbers behind it. It has the starting two numbers predefined as 0 & 1. The series goes on like this: 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377.. Here we illustrate two techniques for the creation of the Fibonacci Series to n terms. The For Loop method & the Recursive Technique. Check them below.
The For Loop technique requires that we create some variables and keep track of the latest two terms('First' & 'Second'). Then we calculate the next term by adding these two terms & setting a new set of two new terms. These terms are the 'Second' & 'Newest'.
using System; using System.Text; using System.Threading.Tasks; namespace Fibonacci_series_Using_For_Loop { class Program { static void Main(string[] args) { int n, first = 0, second = 1, next, c; Console.WriteLine("Enter the number of terms"); n = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("First " + n + " terms of Fibonacci series are:"); for (c = 0; c < n; c++) { if (c <= 1) next = c;
http://www.code-kings.blogspot.com/
Page 23
else { next = first + second; first = second; second = next; } Console.WriteLine(next); } Console.ReadKey(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 24
The recursive technique to a Fibonacci series requires the creation of a function that returns an integer sum of two new numbers. The numbers are one & two less than the number supplied. In this way final output value has each number added twice excluding 0 & 1. Check the program below.
using System; using System.Text; using System.Threading.Tasks; namespace Fibonacci_Series_Recursion { class Program { static void Main(string[] args) { int n, i = 0, c; Console.WriteLine("Enter the number of terms"); n = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("First 5 terms of Fibonacci series are"); for (c = 1; c <= n; c++) { Console.WriteLine(Fibonacci(i)); i++; } Console.ReadKey(); } static int Fibonacci(int n) { if (n == 0) return 0; else if (n == 1) return 1; else return (Fibonacci(n - 1) + Fibonacci(n - 2)); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 25
using System; using System.Text; namespace Print_and_Get_Date_Difference_in_C_Sharp { class Program { static void Main(string[] args) { Console.WriteLine("*******************************************"); Console.WriteLine("********www.code-kings.blogspot.com********"); Console.WriteLine("*******************************************\n"); Console.WriteLine("The Date Today Is:"); DateTime DT = new DateTime(); DT = DateTime.Today.Date; Console.WriteLine(DT.Date.ToString()); Console.WriteLine("Calculate the difference between two dates:\n"); int year, month, day; Console.WriteLine("Enter Start Date"); Console.WriteLine("Enter Year");
http://www.code-kings.blogspot.com/
Page 26
year = Convert.ToInt16(Console.ReadLine().ToString()); Console.WriteLine("Enter Month"); month = Convert.ToInt16(Console.ReadLine().ToString()); Console.WriteLine("Enter Day"); day = Convert.ToInt16(Console.ReadLine().ToString()); DateTime DT_Start = new DateTime(year,month,day); Console.WriteLine("\nEnter End Date"); Console.WriteLine("Enter Year"); year = Convert.ToInt16(Console.ReadLine().ToString()); Console.WriteLine("Enter Month"); month = Convert.ToInt16(Console.ReadLine().ToString()); Console.WriteLine("Enter Day"); day = Convert.ToInt16(Console.ReadLine().ToString()); DateTime DT_End = new DateTime(year, month, day); TimeSpan timespan = DT_End.Subtract(DT_Start); Console.WriteLine("\nThe Difference is:\n"); Console.WriteLine(timespan.TotalDays.ToString() + " Days\n"); Console.WriteLine((timespan.TotalDays / 365).ToString() + " Years"); Console.ReadKey(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 27
namespace Obtain_IP_Address_in_C_Sharp { class Program { static void Main(string[] args) { Console.WriteLine("*************************************"); Console.WriteLine("*****www.code-kings.blogspot.com*****"); Console.WriteLine("*************************************\n"); String StringHost; if (args.Length == 0) { // Getting Ip address of local machine... // First get the host name of local machine. StringHost = System.Net.Dns.GetHostName(); Console.WriteLine("Local Machine Host Name is: " + StringHost); Console.WriteLine(""); } else { StringHost = args[0]; }
http://www.code-kings.blogspot.com/
Page 28
// Then using host name, get the IP address list.. IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(StringHost); IPAddress[] address = ipEntry.AddressList; for (int i = 0; i < address.Length; i++) { Console.WriteLine(""); Console.WriteLine("IP Address Type {0}: {1} ", i, address[i].ToString()); } Console.Read(); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 29
using System; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Turn_Off_Monitor { public partial class Form1 : Form { public Form1() { InitializeComponent(); } [DllImport("user32.dll")] public static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam); private void btnStandBy_Click(object sender, EventArgs e) { IntPtr a = new IntPtr(1); IntPtr b = new IntPtr(0xF170); const int WM_SYSCOMMAND = 0x0112; SendMessage(this.Handle, WM_SYSCOMMAND, b, a); } private void btnMonitorOff_Click(object sender, EventArgs e) { IntPtr a = new IntPtr(2); IntPtr b = new IntPtr(0xF170); const int WM_SYSCOMMAND = 0x0112; SendMessage(this.Handle, WM_SYSCOMMAND, b, a); }
http://www.code-kings.blogspot.com/
Page 30
private void btnMonitorOn_Click(object sender, EventArgs e) { IntPtr a = new IntPtr(-1); IntPtr b = new IntPtr(0xF170); const int WM_SYSCOMMAND = 0x0112; SendMessage(this.Handle, WM_SYSCOMMAND, b, a); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 31
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 32
using System; using System.Text; using System.Threading.Tasks; namespace Linear_Search { class Program { static void Main(string[] args) { Int16[] array = new Int16[100]; Int16 search, c, number; Console.WriteLine("Enter the number of elements in array\n"); number = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter " + number.ToString() + " numbers\n"); for (c = 0; c < number; c++) { array[c] = new Int16(); array[c] = Convert.ToInt16(Console.ReadLine()); } Console.WriteLine("Enter the number to search\n"); search = Convert.ToInt16(Console.ReadLine()); for (c = 0; c < number; c++) { if (array[c] == search) /* if required element found */ { Console.WriteLine(search.ToString() + " is at locn " + (c + 1).ToString() + ".\n"); break; } } if (c == number) Console.WriteLine(search.ToString() + " is not present in array.\n"); Console.ReadLine(); } } }
http://www.code-kings.blogspot.com/
Page 33
Code for Binary Search Technique in C Sharp namespace Binary_Search { class Program { static void Main(string[] args) { int c, first, last, middle, n, search; Int16[] array = new Int16[100]; Console.WriteLine("Enter number of elements\n"); n = Convert.ToInt16(Console.ReadLine()); Console.WriteLine("Enter " + n.ToString() + " integers\n"); for (c = 0; c < n; c++) { array[c] = new Int16(); array[c] = Convert.ToInt16(Console.ReadLine()); } Console.WriteLine("Enter value to find\n"); search = Convert.ToInt16(Console.ReadLine()); first = 0; last = n - 1; middle = (first + last) / 2;
while (first <= last) { if (array[middle] < search) first = middle + 1; else if (array[middle] == search) { Console.WriteLine(search + " found at location " + (middle + 1)); break; } else last = middle - 1; middle = (first + last) / 2; } if (first > last) Console.WriteLine("Not found! " + search + " is not present in the list."); } } }
http://www.code-kings.blogspot.com/
Page 34
private void Form1_Load(object sender, EventArgs e) { // Set initial values txtLength.Text = textBox.Text.Length.ToString(); trkBar1.Maximum = textBox.Text.Length; } private void trackBar1_Scroll(object sender, EventArgs e) { // Set the Max Value of second TrackBar trkBar2.Maximum = textBox.Text.Length - trkBar1.Value; textBox.SelectionStart = trkBar1.Value; txtSelStart.Text = trkBar1.Value.ToString(); textBox.SelectionLength = trkBar2.Value; txtSelEnd.Text = (trkBar1.Value + trkBar2.Value).ToString();
http://www.code-kings.blogspot.com/
Page 35
Let us understand the working of this property with a simple String "ABCDEFGH". Suppose you wanted to select the characters from between B & C and Between F & G ("A B C D E F G H"), you would set the Selection Start to 2 and the Selection Length to 4. As always, the index starts from 0(Zero) therefore the Selection Start would be 0 if you wanted to start before A i.e. include A as well in the selection.
Notice something below: As we move to the right in the First TrackBar (provided the length of the string remains the same), We find that the second TrackBar has a lower range i.e. a reduced Maximum value.
private void trackBar2_Scroll(object sender, EventArgs e) { textBox.SelectionStart = trkBar1.Value; txtSelStart.Text = trkBar1.Value.ToString(); textBox.SelectionLength = trkBar2.Value; txtSelEnd.Text = (trkBar1.Value + trkBar2.Value).ToString(); txtTotChars.Text = trkBar2.Value.ToString();
http://www.code-kings.blogspot.com/
Page 36
textBox.Select(); }
This is only logical. When we move on to the right, we have a higher Selection Start value. Therefore the number of selected characters possible will be lesser than before because the leading characters will be left out from the Selection Start property.
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 37
Matrix Multiplication in C#
Multiply any number of rows with any number of columns Check for Matrices with invalid rows and Columns Ask for entry of valid Matrix elements if value entered is invalid The code has a main class which consists of 3 functions The first function reads valid elements in the Matrix Arrays The second function Multiplies matrices with the help of for loop The third function simply displays the resultant Matrix
http://www.code-kings.blogspot.com/
Page 38
public void ReadMatrix() { Console.WriteLine("\nPlease Enter Details of First Matrix"); Console.Write("\n*Number of Rows in First Matrix : "); int m = int.Parse(Console.ReadLine()); Console.Write("\n*Number of Columns in First Matrix : "); int n = int.Parse(Console.ReadLine()); a = new int[m, n]; Console.WriteLine("\n*Enter the elements of First Matrix : "); for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { try { WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString()); a[i, j] = int.Parse(Console.ReadLine()); Console.WriteLine(" Value Accepted"); } catch { try { Console.WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString()); Console.WriteLine("\nPlease Enter a Valid Value"); a[i, j] = int.Parse(Console.ReadLine()); Console.WriteLine(" Value Accepted"); } catch { Console.WriteLine("\nPlease Enter a Valid Value(Final Chance)"); Console.WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString()); a[i, j] = int.Parse(Console.ReadLine()); Console.WriteLine(" Value Accepted"); } } } } Console.WriteLine("\nPlease Enter Details of Second Matrix"); Console.Write("\n**Number of Rows in Second Matrix :"); m = int.Parse(Console.ReadLine()); Console.Write("\n**Number of Columns in Second Matrix :"); n = int.Parse(Console.ReadLine()); b = new int[m, n]; Console.WriteLine("\n**Please Enter Elements of Second Matrix:"); for (int i = 0; i < b.GetLength(0); i++) { for (int j = 0; j < b.GetLength(1); j++) { try { Console.WriteLine("Enter Element " + (1 + i).ToString() + " " + (1 + j).ToString()); b[i, j] = int.Parse(Console.ReadLine()); Console.WriteLine(" Value Accepted"); } catch { try
http://www.code-kings.blogspot.com/
Page 39
{ Console.WriteLine("\nPlease Enter a Valid Value"); b[i, j] = int.Parse(Console.ReadLine()); Console.WriteLine(" Value Accepted"); } catch { Console.WriteLine("\nPlease Enter a Valid Value(Final Chance)"); b[i, j] = int.Parse(Console.ReadLine()); Console.WriteLine(" Value Accepted"); } } } } } public void PrintMatrix() { Console.WriteLine("\nFirst Matrix:"); for (int i = 0; i < a.GetLength(0); i++) { for (int j = 0; j < a.GetLength(1); j++) { Console.Write("\t" + a[i, j]); } Console.WriteLine(); } Console.WriteLine("\n Second Matrix:"); for (int i = 0; i < b.GetLength(0); i++) { for (int j = 0; j < b.GetLength(1); j++) { Console.Write("\t" + b[i, j]); } Console.WriteLine(); } Console.WriteLine("\n Resultant Matrix by Multiplying First & Second Matrix"); for (int i = 0; i < c.GetLength(0); i++) { for (int j = 0; j < c.GetLength(1); j++) { Console.Write("\t" + c[i, j]); } Console.WriteLine(); } Console.WriteLine("Do You Want To Multiply Once Again (Y/N)"); if (Console.ReadLine().ToString() == "y" || Console.ReadLine().ToString() == "Y" || Console.ReadKey().ToString() == "y" || Console.ReadKey().ToString() == "Y") { MatrixMultiplication mm = new MatrixMultiplication(); mm.ReadMatrix(); mm.MultiplyMatrix(); mm.PrintMatrix(); } else {
http://www.code-kings.blogspot.com/
Page 40
Console.WriteLine("\nMatrix Multiplication\n"); Console.ReadKey(); Environment.Exit(-1); } } public void MultiplyMatrix() { if (a.GetLength(1) == b.GetLength(0)) { c = new int[a.GetLength(0), b.GetLength(1)]; for (int i = 0; i < c.GetLength(0); i++) { for (int j = 0; j < c.GetLength(1); j++) { c[i, j] = 0; for (int k = 0; k < a.GetLength(1); k++) // OR k<b.GetLength(0) c[i, j] = c[i, j] + a[i, k] * b[k, j]; } } } else { Console.WriteLine("\n Number of columns in First Matrix should be equal to Number of rows in Second Matrix."); Console.WriteLine("\n Please re-enter correct dimensions."); Environment.Exit(-1); } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 41
In this program we have a simple DataTable containing a total of 5 columns: Item Name, Item Price, Item Quantity & Item Total. This DataTable is then displayed in the C# datagrid. The fourth & fifth columns have to be calculated as a multiplied value(by multiplying 2nd and 3rd columns). We add multiple rows & let the Tax & Total get calculated automatically through the Expression value of the Column. The application of expressions is simple, just type what you want. For example, if you want the 10% Tax Column to generate values automatically, you can set the Column.Expression as "<Column1> = <Column2> * <Column3> * 0.1", where the Columns are Tax, Price & Quantity respectively. Note a hint that the columns are specified as a decimal type. Finally after all rows have been set, we can apply appropriate filters on the columns in the C# datagrid control. This is accomplished by setting the filter value in one of the three TextBoxes & clicking the corresponding buttons. The Filter expressions are calculated by simply picking up the values from the validating TextBoxes & matching them to their Column name. Note that the text changes dynamically on the Button.Text property allowing you to easily preview a filter value. In this way we achieve the TextBox validation.
namespace Filter_a_DataGridView { public partial class Form1 : Form { public Form1() { InitializeComponent();
http://www.code-kings.blogspot.com/
Page 42
} DataTable dt = new DataTable(); // Form Table that Persists throughout private void Form1_Load(object sender, EventArgs e) { DataColumn Item_Name = new DataColumn("Item_Name", Type.GetType("System.String")); DataColumn Item_Price = new DataColumn("Item_Price", Type.GetType("System.Decimal")); DataColumn Item_Qty = new DataColumn("Item_Qty", Type.GetType("System.Decimal")); DataColumn Item_Tax = new DataColumn("Item_tax", Type.GetType("System.Decimal")); // "Item_Tax" column is calculated (10% Tax) Item_Tax.Expression = "Item_Price * Item_Qty * 0.1";
// Define Tax
DataColumn Item_Total = new DataColumn("Item_Total", // Define Total Type.GetType("System.Decimal")); // "Item_Total" column is calculated as (Price * Qty + Tax) Item_Total.Expression = "Item_Price * Item_Qty + Item_Tax"; dt.Columns.Add(Item_Name); dt.Columns.Add(Item_Price); dt.Columns.Add(Item_Qty); dt.Columns.Add(Item_Tax); dt.Columns.Add(Item_Total); } private void btnInsert_Click(object sender, EventArgs e) { dt.Rows.Add(txtItemName.Text, txtItemPrice.Text, txtItemQty.Text); MessageBox.Show("Row Inserted"); } private void btnShowFinalTable_Click(object sender, EventArgs e) { this.Height = 637; // Extend dgv.DataSource = dt; btnShowFinalTable.Enabled = false; } private void btnPriceFilter_Click(object sender, EventArgs e) { // Creating a new table allows to preserve //original data and work the filters on the new DataTable DataTable NewDT = new DataTable(); NewDT = dt.Copy(); //Apply Filter Value //Create a new DataTable //Copy existing data // // // // // Add 4 Columns to the Datatable
http://www.code-kings.blogspot.com/
Page 43
NewDT.DefaultView.RowFilter = "Item_Price = ' " + txtPriceFilter.Text + " ' "; //Set new table as DataSource dgv.DataSource = NewDT; } private void txtPriceFilter_TextChanged(object sender, EventArgs e) { // Change Button Text Dynamically btnPriceFilter.Text = "Filter DataGridView by Price : " + txtPriceFilter.Text; } private void btnQtyFilter_Click(object sender, EventArgs e) { // Creating a new table allows to preserve //original data and work the filters on the new DataTable DataTable NewDT = new DataTable(); NewDT = dt.Copy(); NewDT.DefaultView.RowFilter = "Item_Qty = ' " + txtQtyFilter.Text + " ' "; dgv.DataSource = NewDT; } private void txtQtyFilter_TextChanged(object sender, EventArgs e) { // Change Button Text Dynamically btnQtyFilter.Text = "Filter DataGridView by Total : " + txtQtyFilter.Text; } private void btnTotalFilter_Click(object sender, EventArgs e) { // Creating a new table allows to preserve //original data and work the filters on the new DataTable DataTable NewDT = new DataTable(); NewDT = dt.Copy(); NewDT.DefaultView.RowFilter = "Item_Total = ' " + txtTotalFilter.Text + " ' "; dgv.DataSource = NewDT; } private void txtTotalFilter_TextChanged(object sender, EventArgs e) { // Change Button Text Dynamically btnTotalFilter.Text = "Filter DataGridView by Total : " + txtTotalFilter.Text; } private void btnFilterReset_Click(object sender, EventArgs e) { DataTable NewDT = new DataTable(); NewDT = dt.Copy(); dgv.DataSource = NewDT; } }
http://www.code-kings.blogspot.com/
Page 44
http://www.code-kings.blogspot.com/
Page 45
** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 46
The file path can be easily chosen with the help of a save file dialog box(SFD). If the file already exists the default mode will be to append the lines to the existing content of the file. The data type of lines to be written can be specified in the parameter supplied to the Write or Write method of the StreaWriter object. Therefore the Write method can have arguments of type Char, Char[], Boolean, Decimal, Double, Int32, Int64, Object, Single, String, UInt32, UInt64.
using System;
namespace StreamWriter { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnChoosePath_Click(object sender, EventArgs e) { if (SFD.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtFilePath.Text = SFD.FileName; txtFilePath.Text += ".txt"; } } private void btnSaveFile_Click(object sender, EventArgs e) { System.IO.StreamWriter objFile = new System.IO.StreamWriter(txtFilePath.Text,true); for (int i = 0; i < txtContents.Lines.Length; i++) { objFile.WriteLine(txtContents.Lines[i].ToString()); } objFile.Close();
http://www.code-kings.blogspot.com/
Page 47
MessageBox.Show("Total Number of Lines Written : " + txtContents.Lines.Length.ToString()); } private void Form1_Load(object sender, EventArgs e) { // Anything } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 48
http://www.code-kings.blogspot.com/
Page 49
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 50
In C Sharp(Dot Net), combo boxes can be used to place key field/s. Working with combo boxes is much easier compared to text boxes. We can easily bind field/s in a data table created in SQL by merely setting some properties in a combo box. Combo box has three main fields that have to be set to effectively add contents of a data field(Column) to the domain of values in the combo box. We shall also learn how to bind data to text boxes from a data source.
First set the Data Source property to the existing data source which could be a dynamically created data table or could be a link to an existing SQL table as we shall see.
Set the Display Member property to the column that you want to display from the table.
Set the Value Member property to the column that you want to choose the value from.
Item Number 1 2 3 4 5
http://www.code-kings.blogspot.com/
The Item Number is the key and the Item Value DEPENDS on it. The aim of this program is to create a DataTable during run-time & display the columns in two combo boxes.The following example shows a two-way dependency i.e. if the value of any combo box changes, the change must be reflected in the other combo box. Two-way updates the target property or the source property whenever either the target property or the source property changes.The source property changes first then triggers an update in the Target property. In Two-way updates either field may act as a Trigger or a Target. To illustrate this, we simply write the code in the Load event of the form. The code is shown below:
namespace Use_Data_Binding { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { //Create The Data Table DataTable dt = new DataTable(); //Set Columns dt.Columns.Add("Item Number"); dt.Columns.Add("Item Name"); //Add Rows/Records dt.Rows.Add("1", "T.V."); dt.Rows.Add("2","Fridge"); dt.Rows.Add("3","Phone"); dt.Rows.Add("4", "Laptop"); dt.Rows.Add("5", "Speakers"); //Set Data Source Property comboBox1.DataSource = dt; comboBox2.DataSource = dt; //Set Combobox 1 Properties comboBox1.ValueMember = "Item Number"; comboBox1.DisplayMember = "Item Number"; //Set Combobox 2 Properties comboBox2.ValueMember = "Item Number"; comboBox2.DisplayMember = "Item Name"; } } }
http://www.code-kings.blogspot.com/
Page 52
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 53
For displaying the Menu, we have to simply check if the right mouse button was pressed. This can be done easily by creating the MouseClick event in the form's Designer.cs file. The MouseEventArgs contains a check to see if the right mouse button was pressed(or left, middle etc.). The Show() method is a little tricky to use. When using this method, the first parameter is the location of the button relative to the X & Y coordinates that we supply next(the second & third arguments). The best method is to place an invisible control at the location (0,0) in the form. Then, the arguments to be passed are the e.X & e.Y in the Show() method. In short : ContextMenuStrip.Show(UnusedControl,e.X,e.Y);
using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_MouseClick(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Right) { contextMenuStrip1.Show(button1,e.X,e.Y); } } string str = "http://www.code-kings.blogspot.com"; private void ToolMenu1_Click(object sender, EventArgs e) { MessageBox.Show("You Have Clicked the First Menu Item", str); } private void ToolMenu2_Click(object sender, EventArgs e) { MessageBox.Show("You Have Clicked the Second Menu Item", str);
http://www.code-kings.blogspot.com/
Page 54
} private void ToolMenu3_Click(object sender, EventArgs e) { MessageBox.Show("You Have Clicked the Third Menu Item", str); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 55
Suppose the namespace of the project is ProjectNameSpace & property is PropertyName. To modify the setting at runtime and subsequently save it :
ProjectNameSpace.Settings.Default.PropertyName = DesiredValue; ProjectNameSpace.Properties.Settings.Default.Save(); The synchronize button overrides any previously saved setting with the ones specified on the page
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/ Page 56
The method Calculate(int x) is first defined as a virtual function int he parent class & later redefined with the override keyword. Therefore, when the function is called, the override version of the method is used. The example below shows the how we can implement polymorphism in C Sharp. There is a base class called PolyClass. This class has a virtual function Calculate(int x) . The function exists only virtually i.e. it has no real existence. The function is meant to redefined once again in each subclass. The redefined function gives accuracy in defining the behavior intended. Thus, the accuracy is achieved on a lower level of abstraction. The four subclasses namely : CalSquare, CalSqRoot, CalCube & CalCubeRoot give a different meaning to the same named function Calculate(int x). When we initialize objects of the base class, we specify the type of object to be created.
namespace Polymorphism { public class PolyClass { public virtual void Calculate(int x) { Console.WriteLine("Square Or Cube ?? Which One ??"); } } public class CalSquare : PolyClass { public override void Calculate(int x) { Console.WriteLine("Square : "); //Calculate the Square of a number Console.WriteLine(Convert.ToString(Convert.ToInt64(x * x ) )); } } public class CalSqRoot : PolyClass { public override void Calculate(int x) { Console.WriteLine("Square Root Is : "); //Calculate the Square Root of a number Console.WriteLine(Convert.ToString(Convert.ToInt64(Math.Sqrt( x)))); }
http://www.code-kings.blogspot.com/
Page 57
} public class CalCube : PolyClass { public override void Calculate(int x) { Console.WriteLine("Cube Is : "); //Calculate the cube of a number Console.WriteLine(Convert.ToString(Convert.ToInt64(x * x * x))); } } public class CalCubeRoot : PolyClass { public override void Calculate(int x) { Console.WriteLine("Cube Square Is : //Calculate the Cube Root of a number Console.WriteLine(Convert.ToString(Convert.ToInt64(Math.Pow(x, (0.3333333333333))))); } } } namespace Polymorphism { class Program { static void Main(string[] args) { PolyClass[] CalObj = new PolyClass[4]; int x; CalObj[0] = new CalSquare(); CalObj[1] = new CalSqRoot(); CalObj[2] = new CalCube(); CalObj[3] = new CalCubeRoot(); foreach (PolyClass CalculateObj in CalObj) { Console.WriteLine("Enter Integer"); x = Convert.ToInt32(Console.ReadLine()); CalculateObj.Calculate( x ); } Console.WriteLine("Aurevoir !"); Console.ReadKey(); } } }
");
http://www.code-kings.blogspot.com/
Page 58
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 59
Properties in C#
Properties are used to encapsulate the state of an object in a class. This is done by creating Read Only, Write Only or Read Write properties. Traditionally, methods were used to do this. But now the same can be done smoothly & efficiently with the help of properties. A property with Get() can be read & a property with Set() can be written. Using both Get() & Set() make a property Read-Write. A property usually manipulates a private variable of the class. This variable stores the value of the property. A benefit here is that minor changes to the variable inside the class can be effectively managed. For example, if we have earlier set an ID property to integer and at a later stage we find that alphanumeric characters are to be supported as well then we can very quickly change the private variable to a string type.
using System; using System.Collections.Generic; using System.Text; namespace CreateProperties { class Properties { //Please note that variables are declared private //which is a better choice vs declaring them as public private int p_id = -1; public int ID { get { return p_id; } set { p_id = value; } } private string m_name = string.Empty; public string Name { get { return m_name; } set { m_name = value; } } private string m_Purpose = string.Empty; public string P_Name {
http://www.code-kings.blogspot.com/
Page 60
get { return m_Purpose; } set { m_Purpose = value; } } } } using System; namespace CreateProperties { class Program { static void Main(string[] args) { Properties object1 = new Properties(); //Set All Properties One by One object1.ID = 1; object1.Name = "www.code-kings.blogspot.com"; object1.P_Name = "Teach C#"; Console.WriteLine("ID " + object1.ID.ToString()); Console.WriteLine("\nName " + object1.Name); Console.WriteLine("\nPurpose " + object1.P_Name); Console.ReadKey(); } } }
http://www.code-kings.blogspot.com/
Page 61
Also, properties can be used without defining a a variable to work with in the beginning. We can simply use get & set without using the return keyword i.e. without explicitly referring to another previously declared variable. These are Auto-Implement properties. The get & set keywords are immediately written after declaration of the variable in brackets. Thus, the property name & variable name are the same.
public class School { public int No_Of_Students{ get; set; } public string Teacher{ get; set; } public string Student{ get; set; } public string Accountant{ get; set; } public string Manager{ get; set; } public string Principal{ get; set; } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 62
Class Inheritance
Classes can inherit from other classes. They can gain Public/Protected Variables and Functions of the parent class. The class then acts as a detailed version of the original parent class(also known as the base class). The code below shows the simplest of examples :
public class A { //Define Parent Class public A() { } } public class B : A { //Define Child Class public B() { } }
In the following program we shall learn how to create & implement Base and Derived Classes. First we create a BaseClass and define the Constructor , SHoW & a function to square a given number. Next , we create a derived class and define once again the Constructor , SHoW & a function to Cube a given number but with the same name as that in the BaseClass. The code below shows how to create a derived class and inherit the functions of the BaseClass. Calling a function usually calls the DerivedClass version. But it is possible to call the BaseClass version of the function as well by prefixing the function with the BaseClass name.
class BaseClass { public BaseClass() { Console.WriteLine("BaseClass Constructor Called\n"); } public void Function() { Console.WriteLine("BaseClass Function Called\n Enter A Single No."); int number = new int(); number = Convert.ToInt32(Console.ReadLine()); number = number * number; Console.WriteLine("Square is : " + number + "\n"); } public void SHoW() { Console.WriteLine("Inside the BaseClass\n"); } }
http://www.code-kings.blogspot.com/
Page 63
class DerivedClass : BaseClass { public DerivedClass() { Console.WriteLine("DerivedClass Constructor Called\n"); } public new void Function() { Console.WriteLine("DerivedClass Function Called\n Enter A Single No."); int number = new int(); number = Convert.ToInt32(Console.ReadLine()); number = Convert.ToInt32(number) * Convert.ToInt32(number) *Convert.ToInt32(number) ; Console.WriteLine("Cube is : " + number + "\n"); } public new void SHoW() { Console.WriteLine("Inside the DerivedClass\n"); } }
class Program { static void Main(string[] args) { DerivedClass dr = new DerivedClass(); dr.Function(); //Call DerivedClass Function ((BaseClass)dr).Function(); //Call BaseClass Version dr.SHoW(); //Call DerivedClass SHoW ((BaseClass)dr).SHoW(); //Call BaseClass Version Console.ReadKey(); } }
http://www.code-kings.blogspot.com/
Page 64
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 65
using System; namespace Playing_with_the_Random_Class { public partial class Form1 : Form { public Form1() { InitializeComponent(); } Random rd = new Random(); private void button1_Click(object sender, EventArgs e) { label1.Text = Convert.ToString(rd.Next(1, 9)); label2.Text = Convert.ToString(rd.Next(1, 9)); label3.Text = Convert.ToString(rd.Next(1, 9));
http://www.code-kings.blogspot.com/
Page 66
if (label1.Text == label2.Text && label1.Text == label3.Text) { MessageBox.Show("U HAVE WON " + "$ " + label1.Text+"00"+ " !!"); } else { MessageBox.Show("Better Luck Next Time"); } } } }
http://www.code-kings.blogspot.com/
Page 67
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 68
AutoComplete Feature in C#
This is a very useful feature for any graphical user interface which makes it easy for users to fill in applications or forms by suggesting them suitable words or phrases in appropriate text boxes. So, while it may look like a tough job; its actually quite easy to use this feature. The text boxes in C Sharp contain an AutoCompleteMode which can be set to one of the three available choices i.e. Suggest , Append or SuggestAppend. Any choice would do but my favourite is the SuggestAppend. In SuggestAppend, Partial entries make intelligent guesses if the So Far typed prefix exists in the list items. Next we must set the AutoCompleteSource to CustomSource as we will supply the words or phrases to be suggested through a suitable data source. The last step includes calling the AutoCompleteCustomSouce.Add() function with the required. This function can be used at runtime to add list items in the box.
using System; namespace Auto_Complete_Feature_in_C_Sharp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { textBox2.AutoCompleteMode = AutoCompleteMode.SuggestAppend; textBox2.AutoCompleteSource = AutoCompleteSource.CustomSource; textBox2.AutoCompleteCustomSource.Add("code-kings.blogspot.com"); } private void button1_Click(object sender, EventArgs e) { textBox2.AutoCompleteCustomSource.Add(textBox1.Text.ToString()); textBox1.Clear(); } } }
http://www.code-kings.blogspot.com/
Page 69
http://www.code-kings.blogspot.com/
Page 70
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 71
There are two things left to be done now. One to insert & then to Retrieve. We create an SQL command in the standard SQL Query format. Therefore, inserting is done by the SQL command: Insert Into <TableName> (Col1, Col2....) Values (Value for Col1, Value for Col2....). Execution of the Command/SQL Query is done by calling the function ExecuteNonQuery(). The execution of a command Triggers the SQL query on the outside and makes permanent changes to the Database. Make sure your connection to the database is open before you execute the query and also that you close the connection after your query finishes.
To Retrieve the data from Table1 , we insert the present values of the table into a DataTable from which we can retrieve & use in our program easily. This is done with the help of a DataAdapter. We fill our temporary DataTable with the help of the Fill(TableName) function of the DataAdapter which fills a http://www.code-kings.blogspot.com/ Page 72
DataTable with values corresponding to the select command provided to it. The select command used here to retreive all the data from the table is: Select * From <TableName> To retreive specific columns use: Select Column1, Column2 From <TableName>
Hints: 1. 2. 3. 4. 5. 6. 7. The Numbering of Rows Starts from an Index Value of 0 (Zero) The Numbering of Columns also starts from an Index Value of 0 (Zero) To learn how to Filter the Column Values Please Read Here When working with SQL Databases use the System.Data.SqlClient namespace Try to create and work with low number of DataTables by simply creating them common for all functions on a form. Try NOT to create a DataTable every-time you are working on a new function on the same form because then you will have to carefully dispose it off. Try to generate the Connection String dynamically by using the Application.StartupPath.ToString() function so that when the Database is situated on another computer the path referred is correct. You can also give a folder or file select dialog box for the user to choose the exact location of the Database which would prove flawless. Try instilling Datatype constraints when creating your Database. You can also implement constraints on your forms(like NOT allowing user to enter alphabets in a number field) but this method would provide a double check & would prove flawless to the integrity of the Database.
8. 9.
using System; using System.Data.SqlClient; namespace Insert_Show { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename="+ Application.StartupPath.ToString() + "\\Database1.mdf;"); private void Form1_Load(object sender, EventArgs e) { MessageBox.Show("Click on Insert Button & then on Show"); }
http://www.code-kings.blogspot.com/
Page 73
private void btnInsert_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand("INSERT INTO Table1 (fld1, fld2, fld3) VALUES ( "'I '" + "," + "' LOVE '" + "," + "' code-kings.blogspot.com'" + ")", con); con.Open(); cmd.ExecuteNonQuery(); con.Close(); } private void btnShow_Click(object sender, EventArgs e) { DataTable table = new DataTable(); SqlDataAdapter adp = new SqlDataAdapter("Select * from Table1", con); con.Open(); adp.Fill(table); MessageBox.Show(table.Rows[0][0] + " " + table.Rows[0][1] + " " + table.Rows[0][2]); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 74
using System; using System.Data.SqlClient; namespace Data_Fetch_In_Table.Net { public partial class Form1 : Form { public Form1() { InitializeComponent(); } SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS; AttachDbFilename= + Application.StartupPath.ToString() + \\Database1.mdf; Integrated Security=True; User Instance=True"); SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommand cmd = new SqlCommand();
http://www.code-kings.blogspot.com/
Page 75
DataTable dt = new DataTable(); private void Form1_Load(object sender, EventArgs e) { SqlDataAdapter adapter = new SqlDataAdapter("select * from Table1",con); adapter.SelectCommand.Connection.ConnectionString = @"Data Source=.\SQLEXPRESS; AttachDbFilename= + Application.StartupPath.ToString() + "\\Database1.mdf;Integrated Security=True; User Instance=True"); con.Open(); adapter.Fill(dt); con.Close(); } private void button1_Click(object sender, EventArgs e) { Int16 x = Convert.ToInt16(textBox1.Text); Int16 y = Convert.ToInt16(textBox2.Text); string current =dt.Rows[x][y].ToString(); MessageBox.Show(current); } } }
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 76
Also on right clicking the Form, the background color is changed to a random color. This is achieved by picking a random value for Red, Blue and Green through the random class and using the function Color.FromArgb(). The Random object gives us a random integer value to feed the Red, Blue & Green values of Color(Which are between 0 and 255 for a 32 bit color interface). The argument e gives us the source for identifying the button pressed which in this case is desired to be MouseButtons.Right.
http://www.code-kings.blogspot.com/
Page 77
using System; namespace Mouse_Paint { public partial class MainForm : Form { public MainForm() { InitializeComponent(); } private Graphics m_objGraphics; Random rd = new Random(); private void MainForm_Load(object sender, EventArgs e) { m_objGraphics = this.CreateGraphics(); } private void MainForm_Close(object sender, EventArgs e) { m_objGraphics.Dispose(); } private void MainForm_Click(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) m_objGraphics.Clear(Color.FromArgb(rd.Next(0,255),rd.Next(0,255),rd.Next(0,25 5))); } private void MainForm_MouseMove(object sender, MouseEventArgs e) { Rectangle rectEllipse = new Rectangle(); if (e.Button != MouseButtons.Left) return; rectEllipse.X = e.X - 1; rectEllipse.Y = e.Y - 1; rectEllipse.Width = 5; rectEllipse.Height = 5; m_objGraphics.DrawEllipse(System.Drawing.Pens.Blue, rectEllipse); } } }
http://www.code-kings.blogspot.com/
Page 78
Please Note : ** Do not Copy & Paste code written here ; instead type it in your Development Environment ** To Comment or ask a question Click Here
http://www.code-kings.blogspot.com/
Page 79
http://www.code-kings.blogspot.com/ Page 80