Sometimes we need a simple way to bind datagridview component to an SQL query and refresh data when the SQL command changes.
1) Drag a DatagridView control to a form. Name it dataGridView1
2) Double click on the form
In the form load event make an SqlConnection
Declare SqlConnection in the global space
SqlConnection connection
SqlDataAdapter adapter;
DataTable dt;
In the form load event open the connection
connection=new SqlConnection(<
connection.open();
In the event handler to refresh the Datagrid write the following
string commandText = "select * from BLAH";
adapter = new SqlDataAdapter(commandText, connection);
dataGridView1.AutoGenerateColumns = true;
dt = new DataTable();
adapter.Fill(dt);
BindingSource b1 = new BindingSource();
b1.DataSource = dt;
dataGridView1.AutoResizeColumns(
DataGridViewAutoSizeColumnsMode.AllCells);
dataGridView1.DataSource = dt;
And Voila..
No comments:
Post a Comment