Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stored procedure in C# datagridview instead of listbox

I have a problem with stored procedures.

This code works (with a ListBox)

private void button4_Click(object sender, EventArgs e)
{
   string connectionString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
   SqlConnection connection = new SqlConnection(connectionString);

   string sqlCmd = "Drie duurste producten";

   SqlCommand cmd = new SqlCommand(sqlCmd, connection);

   cmd.CommandType = CommandType.StoredProcedure;
   cmd.CommandText = sqlCmd;

   connection.Open();

   using (SqlDataReader reader = cmd.ExecuteReader())
   {
      while (reader.Read())
      {
          listBox1.Items.Add(reader.GetValue(0).ToString()); 
      }
   }   

   connection.Close();
}

But how can I add this data to a DataGridView instead of a ListBox?

Thank you!

like image 774
Vedett2011 Avatar asked Dec 04 '25 17:12

Vedett2011


1 Answers

Change to

   ......
   using (SqlDataAdapter adapter = new SqlDataAdapter()) 
   { 
        DataTable dt = new DataTable();
        adapter.SelectCommand = cmd;            { 
        adapter.Fill(dt);
        dataGridView1.DataSource = dt;
   }    
   ......

usually a DataGridView is filled binding a complete datasource to its DataSource property and letting the control to figure out how to configure its columns and the formatting of the values displayed

like image 193
Steve Avatar answered Dec 06 '25 07:12

Steve



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!