Monday, February 7, 2011

Populate Datagrid Using Datareader in C#.Net

try
{
string SQLstr = "Select * from Employee";

SqlConnection con = new SqlConnection("Connection_String");

//Open Connection
con.Open();

SqlCommand com = new SqlCommand(SQLstr, con);
SqlDataReader read = com.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(read);

// finally bind the data to the grid
dataGridView1.DataSource = dt;

// Close Connection
con.Close();
}
catch (Exception ex)
{
MessageBox.Show("Error");
}

Populate Datagrid using data adapter in C# .Net

SqlConnection OCon;

try
{
// Create Insert Query

string SQLstr = "Select * from Employee";

OCon = new SqlConnection("Connection_String");

SqlDataAdapter dataAdapter = new SqlDataAdapter(SQLstr, OCon);

// Populate a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;

dataAdapter.Fill(table);
BindingSource dbBindSource = new BindingSource();
dbBindSource.DataSource = table;

// Resize the DataGridView columns to fit the newly loaded content.
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

// you can make it grid readonly.
dataGridView1.ReadOnly = true;

// finally bind the data to the grid
dataGridView1.DataSource = dbBindSource;

//ONTCon.CloseConn();

}
catch (Exception ex)
{
// Trough Error
}

Send Mail through outlook using C#

To Send Email Using Outlook you need to add refrence of Outlook to your project



using Outlook = Microsoft.Office.Interop.Outlook;

public class ODA_Genral
{
public void sendemail()
{
try
{
// Create the Outlook application.
Outlook.Application objApp = new Outlook.Application();

// Get the NameSpace and Logon information.
Outlook.NameSpace objNS = oApp.GetNamespace("mapi");

// Log on by using a dialog box to choose the profile.
objNS.Logon(System.Reflection.Missing.Value, System.Reflection.Missing.Value, true, true);

// Create a new mail item.
Outlook.MailItem objMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);

// Set the subject.
objMsg.Subject = "Mail Send Using Outlook through C#.net";

// Set HTML Body for you mail.
String HtmlBoday;
HtmlBoday = "Send Mail Through Outlook using C#.Net";

objMsg.HTMLBody = HtmlBoday;

// Add a recipient.
Outlook.Recipients objRecips = (Outlook.Recipients)oMsg.Recipients;

// TODO: Change the recipient in the next line if necessary.
Outlook.Recipient objRecip = (Outlook.Recipient)oRecips.Add("Email ID");
objRecip.Resolve();

// Call Send Method to send the mail.
objMsg.Send();

// Log off from Outlook.
objNS.Logoff();

// Set All Objects to Null.
objRecip = null;
objRecips = null;
objMsg = null;
objNS = null;
objApp = null;
}

// Simple error handling.
catch (Exception ex)
{
Console.WriteLine("{0} Exception Occured. Mail Sending Failed", ex);
}
}
}