How do I Bind Data to a Datagrid in a C# Windows Application?

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

The below code works in a Web application, but does not work in a Windows
application. The DataBind() command only exists for Web forms. How do I write
this code for a Windows app? Can you give me the code on how to do that?

this.sqlConnection1.Open();
this.dreader = this.sqlCommand3.ExecuteReader...
this.DataGrid1.DataSource = dreader;
this.DataGrid1.DataBind();
this.dreader.Close();
this.sqlConnection1.Close();
 
Hi Steve,

You can load the data into a dataset and bind the dataset to a datagrid.

string connectionString = "something";

using (SqlConnection conn = new SqlConnection(connectionString))
{
using (SqlCommand com = new SqlCommand("SELECT * FROM CUSTOMERS", conn))
{
DataSet ds = new DataSet();

using (SqlDataAdapter da = new SqlDataAdapter(com))
{
da.Fill(ds);
dataGrid1.DataSource = ds.Tables[0];
}
}
}

Note, the using block will ensure close and dispose is called on the
objects.
 
a DataReader closes when your connection closes. You need to put the data
into a datatable or some object
and then attach that to the grid datasource.
 
Back
Top