Monday, February 7, 2011

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
}

No comments:

Post a Comment