C# [C Sharp] Programs Version 2.00
C# [C Sharp] Programs Version 2.00
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 #
using System;
namespace Hello_World
{
public partial class FrmHelloWorld : Form
{
public FrmHelloWorld()
{
InitializeComponent();
}
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 #
namespace Advanced_Calculator
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
www.code-kings.blogspot.com Page 5
(Convert.ToInt32(txtY.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();
}
txtFilePath.Text += ".txt";
}
}
www.code-kings.blogspot.com Page 8
objFile.Close();
www.code-kings.blogspot.com Page 9
Drawing with Mouse in C #
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
using System;
using System.Data.SqlClient;
namespace Data_Fetch_In_Table.Net_2._0
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
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);
MessageBox.Show(current);
}
}
}
www.code-kings.blogspot.com Page 13
Insert & Retrieve from Service Based Database
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.
using System;
using System.Data.SqlClient;
namespace Insert_Show
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
{
MessageBox.Show("Click on Insert Button & then on Show");
www.code-kings.blogspot.com Page 14
}
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();
}
textBox2.AutoCompleteSource = AutoCompleteSource.CustomSource;
textBox2.AutoCompleteCustomSource.Add("code-kings.blogspot.com");
}
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();
}
}
}
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.
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");
}
www.code-kings.blogspot.com Page 19
public void SHoW()
{
Console.WriteLine("Inside the BaseClass\n");
}
}
class Program
{
static void Main(string[] args)
{
DerivedClass dr = new DerivedClass();
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;
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
public int ID
{
get
{
return p_id;
}
set
{
p_id = value;
}
www.code-kings.blogspot.com Page 21
}
using System;
namespace CreateProperties
{
class Program
{
static void Main(string[] args)
{
Properties object1 = new Properties();
object1.Name = "www.code-kings.blogspot.com";
www.code-kings.blogspot.com Page 22
Console.ReadKey();
}
}
}
www.code-kings.blogspot.com Page 23
Polymorphism in C#
namespace Polymorphism
{
public class PolyClass
{
public virtual void Calculate(int x)
{
Console.WriteLine("Square Or Cube ?? Which One ??");
}
}
Console.WriteLine(Convert.ToString(Convert.ToInt64(x * 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))));
}
}
Console.WriteLine(Convert.ToString(Convert.ToInt64(x * x * x)));
}
}
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();
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:
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:
*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.
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
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);
}
}
}
}
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.
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.
namespace Use_Data_Binding
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//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");
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.
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#
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();
}
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
}
MessageBox.Show("Row Inserted");
}
dgv.DataSource = dt;
btnShowFinalTable.Enabled = false;
}
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;
}
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