You are on page 1of 80

CSharp [C#] Programs Compilation Ver 4.

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

Hello World Program For C#


This is a small program which shows the basic functionality of C#. The program contains 2 labels. The labels are shown to blink alternatively with the help of two timers. Whenever a timer is enabled,the other timer is relaxed and a label linked with the corresponding timer has its visible property set to true while the other label has its visible property set to false. This simple logic gives us the effect of alternative blinking of the labels. You can set the tick property of the timer to a suitable number. This gives the time in milliseconds between the blinks. A word of caution: do not simply copy paste codes written here instead type it in your IDE. For example to type in the code for the first timer timer1 , double click on the timer1 which gives you a fraction of code ready to begin with and then type in the code within the closed block of curly braces.

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

Create Controls at Runtime in C# 5


Sometimes you might want to create a user control at runtime. There are times when you are not sure of what controls to include during the designing phase of your forms. In these cases what usally is done is that we draw all available controls in the designer and at runtime we simply make the controls invisible during runtime leaving us with workable visible controls. But this is not the right method. What should be done is exactly illustrated below. You should draw the controls at runtime. Yes, you should draw the controls only when needed to save memory.

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

The code below shows how to draw controls:


namespace Create.Controls.At.Runtime { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { TextBox[] tb = new TextBox[7]; for (int i = 0; i <= 6; i++) { tb[i] = new TextBox(); tb[i].Width = 150; tb[i].Left = 20; tb[i].Top = (30 * i) + 30; tb[i].Text = "Text Box Number: " + i.ToString(); this.Controls.Add(tb[i]); tb[i].Show(); } } } }

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

Check for Anagrams in .Net C#


This program shows how you can check if two given input strings are Anagrams or not in CSharp language. Anagrams are two different words or combinations of characters which have the same alphabets and their counts. Therefore a particular set of alphabets can create many permutations of Anagrams. In other words, if we have the same set of characters in two words(strings) then they are Anagrams. We create a function that has input as a character array pair of inputs. When we get the two different sets of characters, we check the count of each alphabet in these two sets. Finally, we tally and check if the value of character count for each alphabet is the same or not in these sets. If all characters occur at the same rate in both the sets of characters, then we declare the sets to be Anagrams otherwise not. See the code below for C#:
using System;

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

How to Write into Windows Registry in C#


The windows registry can be modified using the C# programming interface. In this section we shall see how to write to a known location in the windows registry. The Windows registry consists of different locations as shown below:

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

The output shown below:

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

Convert From Decimal to Binary System


This code below shows how you can convert a given Decimal number to the Binary number system. This is illustrated by using the Binary Right Shift Operator ">>".

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:

[CallerMemberName] a String [CallerFilePath] an Integer [CallerLineNumber] a String

We use Trace.WriteLine() to output information in the trace window. Here is a C# example:


public void TraceMessage(string message, [CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "", [CallerLineNumber] int sourceLineNumber = 0) { Trace.WriteLine("message: " + message); Trace.WriteLine("member name: " + memberName); Trace.WriteLine("source file path: " + sourceFilePath); Trace.WriteLine("source line number: " + sourceLineNumber); } Whenever we call the TraceMessage() method, it outputs the required information as stated above. Note: Use only with optional parameters. Caller Info does not work when you do not use optional parameters. You can use the CallerMemberName in: * Method, Property or Event: They return name of the method, property, or event from which the call originated. * Constructors: They return the String ".ctor" * Static Constructors: They return the String ".cctor" * Destructor: They return the String "Finalize" * User Defined Operators or Conversions: They return generated member name

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

Reverse the Words in a Given String


This simple C# program reverses the words that reside in a string. The words are assumed to be separated by a single space character. The space character along with other consecutive letters forms a single word. Check the program below for details:

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:

int a = remainder(dividend: 10 , divisor:5);

int a = remainder(divisor:5 , dividend: 10);

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:

Func("John Chow", 30, "America"); Func("John Chow", 30);

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

Get Date Difference in C#


Getting differences in two given dates is as easy as it gets. The function used here is the End_Date.Subtract(Start_Date). This gives us a time span that has the time interval between the two dates. The time span can return values in the form of days, years, etc.

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

Obtain Local Host IP in C#


This program illustrates how we can obtain the IP address of Local Host. If a string parameter is supllied in the exe then the same is used as the local host name. If not then the local host name is retrieved and used. See the code below:

using System; using System.Net;

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

Monitor Turn On/Off/StandBy in C#


You might want to change your display settings in a running program. The code behind requires the Import of a Dll & execution of a function SendMessage(,,,) by supplying 4 parameters. The value of the fourth parameter having values 0, 1 & 2 has the monitor in the states ON, STAND BY & OFF respectively. The first parameter has the value of the valid window which has received the handle to change the monitor state. This must be an active window. You can see the simple code below:

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

Search Techniques: Linear & Binary


Searching is needed when we have a large array of some data or objects & need to find the position of a particular element. We may also need to check if an element exists in a list or not. While there are built in functions that offer these capabilities, they only work with predefined datatypes. Therefore there may the need for a custom function that searches elements & finds the position of elements. Below you will find two search techniques viz. Linear Search & Binary Search implemented in C#. The code is simple & easy to understand & can be modified as per need.

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

Code for Linear Search Technique in C Sharp

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

Working With Strings: The Selection Property


This Program in C# 5 shows the use of the Selection property of the TextBox control. This property is accompanied with the Select() function which must be used to reflect changes you have set to the Selection properties. As you can see, the form also contains two TrackBars. These TrackBars actually visualize the Selection property attributes of the TextBox. There are two Selection properties mainly: Selection Start & Selection Length. These two properties are shown through the current value marked on the TrackBar.

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

txtTotChars.Text = trkBar2.Value.ToString(); textBox.Select(); }

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

DataGridView Filter & Expressions C#


Often we need to filter a DataGridView in our database programs. The C# datagrid is the best tool for database display & modification. There is an easy shortcut to filtering a DataTable in C# for the datagrid. This is done by simply applying an expression to the required column. The expression contains the value of the filter to be applied. The filtered DataTable must be then set as the DataSource of the DataGridView.

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 // // the input // // Columns

// 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

Stream Writer Basics


The StreamWriter is used to write data to the hard disk. The data may be in the form of Strings, Characters, Bytes etc. Also you can specify he type of encoding that you are using. The Constructor of the StreamWriter class takes basically two arguments: The first one is the actual file path with file name that you want to write & the second one specifies if you would like to replace or overwrite an existing file.The StreamWriter creates objects that have interface with the actual files on the hard disk and enable them to be written to text or binary files. In this example we write a text file to the hard disk whose location is chosen through a save file dialog box.

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

Send an Email through C#


The .Net Framework has a very good support for web applications. The System.Net.Mail can be used to send Emails very easily. All you require is a valid Username & Password. Attachments of various file types can be very easily attached with the body of the mail. Below is a function shown to send an email if you are sending through a gmail account. The default port number is 587 & is checked to work well in all conditions. The MailMessage class contains everything you'll need to set to send an email. The information like From, To, Subject, CC etc. Also note that the attachment object has a text parameter. This text parameter is actually the file path of the file that is to be sent as the attachment. When you click the attach button, a file path dialog box appears which allows us to choose the file path(you can download the code below to watch this).
public void SendEmail() { try { MailMessage mailObject = new MailMessage(); SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com"); mailObject.From = new MailAddress(txtFrom.Text); mailObject.To.Add(txtTo.Text); mailObject.Subject = txtSubject.Text; mailObject.Body = txtBody.Text; if (txtAttach.Text != "") // Check if Attachment Exists { System.Net.Mail.Attachment attachmentObject; attachmentObject = new System.Net.Mail.Attachment(txtAttach.Text); mailObject.Attachments.Add(attachmentObject); } SmtpServer.Port = 587; SmtpServer.Credentials = new System.Net.NetworkCredential(txtFrom.Text, txtPassKey.Text); SmtpServer.EnableSsl = true; SmtpServer.Send(mailObject); MessageBox.Show("Mail Sent Successfully"); } catch (Exception ex) { MessageBox.Show("Some Error Plz Try Again", "http://www.codekings.blogspot.com"); } }

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

Use Data Binding in C#


Data Binding is indispensable for a programmer. It allows data(or a group) to change when it is bound to another data item. The Binding concept uses the fact that attributes in a table have some relation to each other. When the value of one field changes, the changes should be effectively seen in the other fields. This is similar to the Look-up function in Microsoft Excel. Imagine having multiple text boxes whose value depend on a key field. This key field may be present in another text box. Now, if a value in the Key field changes, the change must be reflected in all other text boxes.

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.

Consider a table shown below:

Item Number 1 2 3 4 5
http://www.code-kings.blogspot.com/

Item Name T.V. Fridge Phone Laptop Speakers


Page 51

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

Right Click Menu in C#


Are you one of those looking for the Tool called 'Right Click Menu' ? Well, stop looking. Formally known as the Context Menu Strip in .Net Framework, it provides a convenient way to create the Right Click menu.Start off by choosing the tool named ContextMenuStrip in the Toolbox window, under the Menus & Toolbars tab. Works just like the Menu tool, Add & Delete items as you desire. Items include Textbox, Combobox or yet another Menu Item.

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

Save Custom User Settings & Preferences


Your C# application settings allow you to store and retrieve custom property settings and other information for your application. These properties & settings can be manipulated at runtime using ProjectNameSpace.Settings.Default.PropertyName. The .NET Framework allows you to create and access values that are persisted between application execution sessions. These settings can represent user preferences, or valuable information the application needs to use or should have. For example, you might create a series of settings that store user preferences for the color scheme of an application. Or you might store a connection string that specifies a database that your application uses. Please note that whenever you create a new Database, C# automatically creates the connection string as a default setting. Settings allow you to both persist information that is critical to the application outside of the code, and to create profiles that store the preferences of individual users. They make sure that no two copies of an application look exactly the same & also that users can style the application GUI as they want. To create a setting : *Right Click on the project name in the explorer window; Select Properties *Select the settings tab on the left *Select the name & type of the setting that required *Set default values in the value column

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

Basics of Polymorphism Explained


Polymorphism is one of the primary concepts of Object Oriented Programming. There are basically two types of polymorphism (i) RunTime (ii) CompileTime. Overriding a virtual method from a parent class in a child class is RunTime polymorphism while CompileTime polymorphism consists of overloading identical functions with different signatures in the same class. This program depicts Run Time Polymorphism.

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.

using System; using System.Collections.Generic; using System.Text;

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

Random Generator Class in C#


The C Sharp language has a good support for creating random entities such as integers, bytes or doubles. First we need to create the Random Object. The next step is to call the Next() function in which we may supply a minimum and maximum value for the random integer. In our case we have set the minimum to 1 and maximum to 9. So, each time we click the button we have a set of random values in the three labels. Next, we check for the equivalence of the three values; and if they are then we append two zeroes to the text value of the label thereby increasing the value 100 times. Finally we use the MessageBox() to show the amount of money won.

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

Insert & Retrieve from Service Based Database


Now, we go a bit deeper in the SQL database in C# as we learn how to Insert as well as Retrieve a record from a Database. Start off by creating a Service Based Database which accompanies the default created form named form1. Click Next until finished. A Dataset should be automatically created. Next double click on the Database1.mdf file in the solution explorer (Ctrl + Alt + L) and carefully select the connection string. Format it in the way as shown below by adding the @ sign and removing a couple of "=" signs in between. The connection string in .Net Framework 4.0 does not need the removal of @ & "=" signs. The String is generated perfectly ready to use. This step only applies to .Net Framework 1.0 & 2.0.

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

Fetch Data from a Specified Position


Fetching data from a table in C Sharp is quite easy. It First of all requires creating a connection to the database in the form of a connection string that provides an interface to the database with our development environment. We create a temporary DataTable for storing the database records for faster retrieval as retrieving from the database time and again could have an adverse effect on the performance. To move contents of the SQL database in the DataTable we need a DataAdapter. Filling of the table is performed by the Fill() function. Finally the contents of DataTable can be accessed by using a double indexed object in which the first index points to the row number and the second index points to the column number starting with 0 as the first index. So, if you have 3 rows in your table then they would be indexed by row numbers 0 , 1 & 2.

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

Drawing with Mouse in C#


This C# Windows Forms tutorial is a bit advanced program which shows a glimpse of how we can use the graphics object in C#. Our aim is to create a form and paint over it with the help of the mouse just as a 'Pencil'. Very similar to the 'Pencil' in MS Paint. We start off by creating a graphics object which is the form in this case. A graphics object provides us a surface area to draw to. We draw small ellipses which appear as dots. These dots are produced frequently as long as the left mouse button is pressed. When the mouse is dragged, the dots are drawn over the path of the mouse. This is achieved with the help of the MouseMove event which means the dragging of the mouse. We simply write code to draw ellipses each time a MouseMove event is fired.

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

Thank You For Reading

http://www.code-kings.blogspot.com/ Page 80

You might also like