Friday, April 3, 2009

C Sharp Source Code #1

Collapses and hides sections of code using #Region Directive

#Region "Private Member Variables"
Private _productID As Integer
Private _productName As String
Private _quantityPerUnit As String
#End Region

Difference between DataSet Copy and Clone

DataSet.Clone copies only the datatable structure with its schema, relations, and constraints of the dataset not the data, where as DataSet.Copy copy the both.

DataSet dsEmployees = PopulateEmployeeData();
DataSet myCloneDS = dsEmployees.Clone();

public DataSet PopulateEmployeeData()
DataTable dtEmployee = new DataTable();
DataColumn myCol;
DataRow myRow;

myCol = new DataColumn();
myCol.ColumnName = "EmployeeID";

myCol = new DataColumn();
myCol.ColumnName = "EmployeeName";

//Add some rows to employee datatable
for (int i = 0; i < 10; i++)
myRow = dtEmployee.NewRow();
myRow["EmployeeID"] = i;
myRow["EmployeeName"] = "EmployeeName " + i.ToString();


DataSet dsEmployees = new DataSet();

return dsEmployees;

Get the Virtual Directory path

using System.DirectoryServices; //include System.DirectoryServices

System.DirectoryServices.DirectoryEntry objDirectoryEntry = new DirectoryEntry("IIS://"
+ Server.MachineName + "/W3SVC/1/Root/" + virtualDirAppName);

string VirDirPath = objDirectoryEntry.Properties["Path"].Value.ToString();

Log the Error Messages to an I/O File

public void WriteLog(string strMessage)
StreamWriter SW;
SW = File.AppendText("C:\\MyTextFile.txt");

Set the required element in the Combo box.

ddlCity.SelectedIndex = ddlCity.Items.IndexOf(ddlCity.Items.FindByText(“Bangalore”));

Below code would also help you:

Int32 itemIndex = comboEmployeeName.FindStringExact(EmployeeName);

if (itemIndex >= 0)
comboEmployeeName.SelectedIndex = itemIndex;

Making the cursor to wait for processing


this.Cursor = Cursors.WaitCursor;

\\Processing code goes here


catch (Exception objException){ }

finally{this.Cursor = Cursors.Default;}

Give the month in 00 format (Zero filling format)

for January it should be 01 instead of 1. Just format the month as below:


Validate for null value in a Property

public string Name
if ( strName == null )
throw new Exception("Exception: Name is null");

return strName;

Using IsNullOrEmpty to check if the string object is null or empty.

if (!string.IsNullOrEmpty(myString))

//Do Something


SendKeys or text to a notepad application.

public void sendKeysTest()
Process myProcess = Process.Start(@"notepad.exe");


if (myProcess.Responding)
SendKeys.SendWait("This text is send through some other application to notepad.");


Connect to Database getting the connection string from App.config

public SqlConnection ConnectToDatabase()
string connectionString;
SqlConnection connection = null;
connectionString = ConfigurationManager.ConnectionStrings["MasterConnectionString"].ConnectionString;
// Open database connection.
connection = new SqlConnection(connectionString);
return connection;
catch (SqlException ex)
throw ex;

Verify and Validate the IP Address

if (mTxtIPAddress.Text.Trim() != string.Empty)
System.Net.IPAddress ip;
ip = System.Net.IPAddress.Parse(mTxtIPAddress.Text);
catch (FormatException frmtEx)
MessageBox.Show("Please specify valid value for IP.", "WebAgent Dialog", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
vallidate = false;

Get the Application Path


Set the default button in the messagebox from Yes No options.

myAns = MessageBox.Show(sb.ToString(), "Send Confirmation",MessageBoxButtons.YesNo, MessageBoxIcon.None,MessageBoxDefaultButton.Button2);

Incorporating a Variable value in output

Console.WriteLine("Hello {0} {1}!", FirstName, LastName);

Escape sequences in C#

\n new line (linefeed)
\b backspace
\t tab
\r carriage return

Generating a Random number

double myDouble;
Random oRandom = new Random();
myDouble = (oRandom.NextDouble() * 6) + 1;

No comments:

Post a Comment