Click here to Skip to main content
15,888,968 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am new to window applicaiton and using the following code to datagridview binding:
SqlDataAdapter adp = new SqlDataAdapter("Select * from tblcnt", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
DataSet ds = new DataSet();
adp.Fill(ds);           
dataGridView1.DataSource = ds;
dataGridView1.AutoGenerateColumns = true;


Please correct this and provide the detailed explanation.

Regards!
Aman
Posted
Comments
Aman4.net 7-Jan-11 1:00am    
Please correct this if here is any error.

Hope Grid View[^]will help you.
 
Share this answer
 
That's good but you need to provide command object in costructor of DataAdapter.

See all my correction your program with Green Comments.

C#
SqlDataAdapter adp = new SqlDataAdapter(new SqlCommand("Select * from tblcnt", ConfigurationManager.ConnectionStrings["cn"].ConnectionString));
//See I've changed here SqlDataAdapter constuctor.
DataSet ds = new DataSet();
adp.Fill(ds);           
//Keep this things before for assigning value to any grid properties
dataGridView1.AutoGenerateColumns = true;
dataGridView1.DataSource = ds;
//you've just forgot to bind datagridview
dataGridView1.DataBind();
 
Share this answer
 
you are not setting object reference to an instance of object because you are just assigning dataset object to datasource which is not enough to bind Data.
you can use given code to bind your data to datagridview

SqlDataAdapter da = new SqlDataAdapter("Select * from tblcnt", ConfigurationManager.ConnectionStrings["cn"].ConnectionString);
            DataSet ds = new DataSet();
            da.Fill(ds,"tblcnt");
            DataTable dt = ds.Tables["tblcnt"];
            dataGridView1.DataSource = dt.DefaultView;


try it..
 
Share this answer
 
v3
check here[^]
 
Share this answer
 
private void Form1_Load(object sender, EventArgs e)
{
string strCon = "Data Source=dbServer;Initial Catalog=testDB;Integrated Security=True";
string strSQL = "";

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

// Populating a new data table and bind it to the BindingSource.
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
dbBindSource.DataSource = table;


dbGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

dbGridView.ReadOnly = true;

dbGridView.DataSource = dbBindSource;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900