How do I populate a "DataGridView" (not gridview) using SqlDataReader and not SqlDataAdapter on C#
-
Sunday, July 10, 2011 3:45 PM
I'm studying about ado.net and I'm just curious on how to populate a datagridview on C# using a DataReader, most of the examples I've seen and used implements a DataAdapter. like the code below:
string mat = "Select * from Material Where ProductId = '" + textBox1.Text + "'"; SqlDataAdapter Adapter2 = new SqlDataAdapter(mat, constring); DataTable dtmat = new DataTable(); Adapter2.Fill(dtmat); dataGridView1.DataSource = dtmat;Below is my current attempt to populate a datagridview using a datareader
private void button1_Click(object sender, EventArgs e) { string conStr = @"Data Source=randel-pc;Initial Catalog=DBS-CON;Integrated Security=True"; SqlConnection sConn = new SqlConnection(conStr); sConn.Open(); string get = "Select * From Product"; SqlCommand scomm = new SqlCommand(get, sConn); SqlDataReader sdr = scomm.ExecuteReader(); while(sdr.Read()) { //dataGridView1.Columns.Add("PrdouctID","prodID"); //dataGridView1.Rows.Add(); }
Randel Ramirez
All Replies
-
Sunday, July 10, 2011 5:55 PM
Hi randelramirez1;
All that is needed is to connect the Data reader to a binding source and then connect the binding source to the data grid view and that is it. Modify your code as follows and it should work fine.
SqlCommand scomm = new SqlCommand(get, sConn); SqlDataReader sdr = scomm.ExecuteReader(); // Create a BindingSource object BindingSource bs = new BindingSource(); // Assign the reader to the binding source bs.DataSource = sdr; // Assign the BindingSource to the DataGridView DataSource dataGridView1.DataSource = bs; sConn.Close();
Fernando (MCSD)
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marked As Answer by randelramirez1 Monday, July 11, 2011 4:30 AM
-
Sunday, July 10, 2011 10:04 PM
Hi
You can use this
http://www.codeproject.com/KB/grid/dataGridview-DataReader.aspx
you will learn alot from it
If a post answers your question, please click "Mark As Answer" on that post and "Mark as Helpful".- Marked As Answer by randelramirez1 Monday, July 11, 2011 4:30 AM

