0% found this document useful (0 votes)
3 views

C# [C Sharp] Programs Version 2.00

The document is a C# programming guide that covers various topics including basic programs like 'Hello World', an advanced calculator, and functionalities such as data fetching from a database and implementing an autocomplete feature. Each section provides code examples and explanations for creating applications using C#. It serves as a resource for learning C# programming concepts and practical implementations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

C# [C Sharp] Programs Version 2.00

The document is a C# programming guide that covers various topics including basic programs like 'Hello World', an advanced calculator, and functionalities such as data fetching from a database and implementing an autocomplete feature. Each section provides code examples and explanations for creating applications using C#. It serves as a resource for learning C# programming concepts and practical implementations.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

C# [C Sharp] Codes 2nd Edition

Hello World___________________________________________________________________3
Advanced Calculator_______________________________________________________5
Stream Writer________________________________________________________________8
Mouse Drawing____________________________________________________________10
Fetch Data from Table___________________________________________________12
Insert into Service Database___________________________________________14
Autocomplete Feature___________________________________________________17
Random Generator_______________________________________________________18
Class Inheritance__________________________________________________________19
Properties___________________________________________________________________21
Polymorphism_____________________________________________________________24
Embed & Execute exe___________________________________________________26

www.code-kings.blogspot.com Page 1
Custom User Settings_____________________________________________________27
Right Click Menu___________________________________________________________28
Use Data Binding__________________________________________________________30
Send Email in C_____________________________________________________________33
DataGridView Filter & Expression____________________________________35

www.code-kings.blogspot.com Page 2
Hello World Program For C #

This is a 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;
}

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 !";

www.code-kings.blogspot.com Page 3
}
else
if (cmdClickHere.Text = "STOP !")
{
timer1.Enabled = false;
timer2.Enabled = false;
cmdClickHere.Text = "Click Here !";
}
}
}
}

www.code-kings.blogspot.com Page 4
An Advanced Calculator in C #

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 calci 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
have to 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 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).

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.ToInt32(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)) *

www.code-kings.blogspot.com Page 5
(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)));
}

private void TanX_Click(object sender, EventArgs e)


{
txtTanX.Text = " Tan " + txtX.Text + " = " +
Convert.ToString(Math.Tan(Convert.ToDouble(txtX.Text)));
}
}
}

www.code-kings.blogspot.com Page 6
www.code-kings.blogspot.com Page 7
Stream Writer for C #

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. 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());
}

www.code-kings.blogspot.com Page 8
objFile.Close();

MessageBox.Show("Total Number of Lines Written : " +


txtContents.Lines.Length.ToString());
}

private void Form1_Load(object sender, EventArgs e)


{
// Anything
}
}
}

www.code-kings.blogspot.com Page 9
Drawing with Mouse in C #

This 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. The argument e gives us the source for identifying the
button pressed which in this case is desired to be MouseButtons.Right.

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,255)));
}
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;

www.code-kings.blogspot.com Page 10
m_objGraphics.DrawEllipse(System.Drawing.Pens.Blue, rectEllipse);
}
}
}

www.code-kings.blogspot.com Page 11
Fetch Data from Table

Fetching data from a table in C Sharp is quite easy. It 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_2._0
{
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();
DataTable dt = new DataTable();

private void Form1_Load(object sender, EventArgs e)


{

SqlDataAdapter adapter = new SqlDataAdapter("select * from Table1",con);

adapter.SelectCommand.Connection.ConnectionString = con;
con.Open();

adapter.Fill(dt);

con.Close();
}

www.code-kings.blogspot.com Page 12
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);

}
}
}

www.code-kings.blogspot.com Page 13
Insert & Retrieve from Service Based Database

Now , we go a bit deeper with the SQL database in C# as we shall see


how to Insert as well as Retrieve a record from the 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 a way as shown below:

 Add the @ sign in the very beginning.

 Removing a couple of "=" signs in between.

There are two things to be done. First one insert & then Retrieve. We
create an SQL command in the standard format. Therefore, inserting is
done by the SQL command Insert Into <TableName> (....) Values (.....)
. Execution of the command is done by the function ExecuteNonQuery .
Make sure your connection to the database is open before you execute
the query.

To Retrieve the data from Table1 , we need to insert the present


values of the table into a table from which we can retrieve easily.
This is done by the help of a DataAdapter. We fill our temporary table
by the help of the Fill() function of the DataAdapter which fills a
table with values corresponding to the select command provided to it.

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; Integrated Security=True; User Instance=True");

private void Form1_Load(object sender, EventArgs e)

{
MessageBox.Show("Click on Insert Button & then on Show");

www.code-kings.blogspot.com Page 14
}

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]);
}
}
}

www.code-kings.blogspot.com Page 15
www.code-kings.blogspot.com Page 16
AutoComplete Feature in C Sharp ( 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();
}
}
}

www.code-kings.blogspot.com Page 17
Playing with the Random Generator Class in C Sharp ( C # )

The C Sharp language has a good support for creating random entities
such as integers, bytes or doubles. A random desired value between two
extremes can be achieved easily. If only a maximum value is defined
then the default minimum is zero. We first create a Random object from
the Random class. 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));

if (label1.Text == label2.Text && label1.Text == label3.Text)


{
MessageBox.Show("U HAVE WON " + "$ " + label1.Text+"00"+ " !!");
}
else
{
MessageBox.Show("Better Luck Next Time");
}
}

}
}

www.code-kings.blogspot.com Page 18
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 base class gives us a general idea of the type objects to
be worked with. The child classes have some added functionality or
completely redefine existing functions or definitions.

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");
}

www.code-kings.blogspot.com Page 19
public void SHoW()
{
Console.WriteLine("Inside the BaseClass\n");
}
}

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();
}
}

www.code-kings.blogspot.com Page 20
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 achieved smoothly & efficiently with the help of
properties.

Properties can be used with/without defining a variable to work with. 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 a variable in brackets.
Thus, the property name & variable name are the same.

using System;

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; }
}

A property with Get() can be read & a property with Set() can be written. Using both
Get() & Set() makes 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;

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;
}

www.code-kings.blogspot.com Page 21
}

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


{
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);

www.code-kings.blogspot.com Page 22
Console.ReadKey();
}
}
}

www.code-kings.blogspot.com Page 23
Polymorphism in C#

Polymorphism is one of the primary concepts in 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 the


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 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 be 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)
{

www.code-kings.blogspot.com Page 24
Console.WriteLine("Square Root Is : ");
//Calculate the Square Root of a number

Console.WriteLine(Convert.ToString(Convert.ToInt64(Math.Sqrt(x))));
}
}

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();
}
}
}

www.code-kings.blogspot.com Page 25
Embed & Execute Resource Files (exe, mp3, txt, etc.)
We now learn how to embed files internally into a program. The file can be any type i.e. with
any extension. The fun part is that the file's visibility to the user can be controlled & can also be
moved to any location within the hard disk. Thus we can execute exe's on a completely different
process/thread. If we have programs that were built before & need reuse or desired to be run
parallel, this is the technique.The process is explained as follows:

1. Right click on the project name and select Properties.

2. Click on the Resources tab on the Left.

3. Click on Add Resource >> Add Existing File.

4. Choose the file location on your HDD & u will see the file available in the Solution Explorer.

5. You will be able to access this file using a funtion shown below:

string exePath = Application.StartupPath.ToString()+"\\FileName.exe";


public void ExtractResource(string resource)
{
Stream stream = GetType().Assembly.GetManifestResourceStream(resource);
byte[] bytes = new byte[(int)stream.Length];
stream.Read(bytes, 0, bytes.Length);
File.WriteAllBytes(exePath, bytes);
System.Diagnostics.Process.Start(exePath);
}

Use this function as explained

*Call the ExtractResource() function whenever you want to run an embedded resource file.

*The string 'resource' is the exact file name including the extension(.exe, .txt, etc).

*The string 'path' is where the resource will be extracted before it is run. The resource
will be extracted only when needed/called.

*If the File is not an exe then the default program will be used to launch the file.

*The above function actually extracts the resource in the execution path/folder
itself(the value of exePath). The value can be anything suitable or even custom. The
selection can be made by the choose folder dialog box.

*The System.Diagnostics.Process.Start(exePath) function executes an executable file from


HDD whose location is given in the parameter.

www.code-kings.blogspot.com Page 26
Save Custom User Settings & Preferences

Application settings allow you to store and retrieve property settings and other information for
your application dynamically. The .NET Framework allows you to create and access values that
are persisted between application execution sessions. These values are called settings. Settings
can represent user preferences, or valuable information the application needs to use. For
example, you might create a series of settings that store user preferences for the color scheme of
an application. Or you might store the connection string that specifies a database that your
application uses. 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.

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 on the top left corner of the properties tab overrides any previously
saved setting with the ones specified on the page.

www.code-kings.blogspot.com Page 27
Create a Right Click Menu

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);
// Snapshot of code from Form1.Designer.cs
// ToolMenu1
//
this.ToolMenu1.Name = "ToolMenu1";
this.ToolMenu1.Size = new System.Drawing.Size(188, 34);
this.ToolMenu1.Text = "CODE-KINGS.";
//////////////////////////////////////////////////////////////////////
// Write This Line Below
this.ToolMenu1.Click += new System.EventHandler(this.ToolMenu1_Click);
//////////////////////////////////////////////////////////////////////
// ToolMenu2
//
//////////////////////////////////////////////////////////////////////
// Write This Line Below
this.ToolMenu2.Click += new System.EventHandler(this.ToolMenu2_Click);
//////////////////////////////////////////////////////////////////////
// ToolMenu3
//
//////////////////////////////////////////////////////////////////////
// Write This Line Below
this.ToolMenu3.Click += new System.EventHandler(this.ToolMenu3_Click);
//////////////////////////////////////////////////////////////////////

www.code-kings.blogspot.com Page 28
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(341, 262);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "http://www.code-kings.blolgspot.com";
this.MouseClick += new
System.Windows.Forms.MouseEventHandler(this.Form1_MouseClick);
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
// Code from Form1.cs
using System;

namespace RightClickMenu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_MouseClick(object o, MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Right)
{
contextMenuStrip1.Show(button1,e.X,e.Y);
}
}

string str = "http://www.code-kings.blolgspot.com";

// Write This Line Below


private void ToolMenu1_Click(object o, EventArgs e)
{
MessageBox.Show("You have Clicked the First Menu Item", str);
}

// Write This Line Below


private void ToolMenu2_Click(object o, EventArgs e)
{
MessageBox.Show("You have Clicked the Second Menu Item", str);
}

// Write This Line Below


private void ToolMenu3_Click(object o, EventArgs e)
{
MessageBox.Show("You have Clicked the Third Menu Item", str);
}

}
}

www.code-kings.blogspot.com Page 29
Use Data Binding
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 in one field changes, the changes must be
effectively seen in 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 the value in the Key field changes, the change must
be reflected in all other text boxes.

In C Sharp (Dot Net), We may use combo boxes 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.

 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:

www.code-kings.blogspot.com Page 30
The Item Number is the key and the Item Value DEPENDS on it. Now we
aim to make a program in which we create a DataTable during runtime &
display the columns in two combo boxes. If the value of any combo box
changes then the change must be reflected in the other combo box.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";
}
}
}

www.code-kings.blogspot.com Page 31
www.code-kings.blogspot.com Page 32
Send 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.

public void SendEmail()


{
try
{
//Create a mail object
MailMessage mailObject = new MailMessage();

SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

//Set your email


mailObject.From = new MailAddress(txtFrom.Text);

//Set your recipient


mailObject.To.Add(txtTo.Text);

//Set the mail subject


mailObject.Subject = txtSubject.Text;

//Set main body


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);

www.code-kings.blogspot.com Page 33
MessageBox.Show("Mail Sent Successfully");
}
catch (Exception ex)
{
MessageBox.Show("Some Error Plz Try Again",
"http://www.code-kings.blogspot.com");

}
}

www.code-kings.blogspot.com Page 34
DataGridView Filter & Expressions in C#

Often we need to filter a DataGridView in our programs. There is an


easy shortcut to filtering a DataTable in C#. 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 the program we have a simple DataTable containing a total of 4


columns. Item Name, Item Price, Item Quantity & Item Total. The fourth
column has to be calculated as a multiplied value(by multiplying 2nd
and 3rd columns). We add multiple rows & let the total get calculated
automatically through the Expression value of the Column. Note that
the columns are specified as a decimal type.

Finally after all rows have been set, we can apply appropriate filters
on the columns. This is accomplished by setting the filter value in
one of the three TextBoxes & clicking the corresponding buttons. Note
that the text changes dynamically on the button allowing you to easily
preview the filter value.

namespace Filter_a_DataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

DataTable dt = new DataTable();

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_Total = new DataColumn("Item_Total",


Type.GetType("System.Decimal"));

// "Item_Total" column needs to be calculated


Item_Total.Expression = "Item_Price * Item_Qty";

www.code-kings.blogspot.com Page 35
dt.Columns.Add(Item_Name); // Add 4
dt.Columns.Add(Item_Price); // Columns
dt.Columns.Add(Item_Qty); // to the
dt.Columns.Add(Item_Total); // Datatable
}

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(); //Create a new DataTable


NewDT = dt.Copy(); //Copy existing data

//Apply Filter Value


NewDT.DefaultView.RowFilter = "Item_Price = ' " + txtItemPrice.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;
}

www.code-kings.blogspot.com Page 36
private void txtQtyFilter_TextChanged(object sender, EventArgs e)
{
// Change Button Text Dynamically
btnQtyFilter.Text = "Filter DataGridView by Price : " + 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 Price : " +
txtTotalFilter.Text;

private void btnFilterReset_Click(object sender, EventArgs e)


{
DataTable NewDT = new DataTable();
NewDT = dt.Copy();
dgv.DataSource = NewDT;
}
}
}

www.code-kings.blogspot.com Page 37
www.code-kings.blogspot.com Page 38
www.code-kings.blogspot.com Page 39
Come & Visit Us
Have a comment
Your presence Matters
!

www.code-kings.blogspot.com Page 40

You might also like