-1

I have a list of query parameters(selected items from checklistbox). I need to pass each parameter to a query(sql server select statement) and bind results to grid view. I am trying to add rows to datatable using datareader. Can some one please provide sample code base on how to code this requirement?

tmk
  • 1
  • This may help you https://www.aspsnippets.com/Articles/Populate-Bind-DataGridView-using-DataReader-in-Windows-Forms-WinForms-Application-using-C-and-VBNet.aspx – Ravi Kanth Mar 14 '17 at 06:59
  • Thanks for your help on this Ravi! I tried this but gridview results are being overridden by latest query execution results and I don't see previous results on it. I am trying to use Rows.Add Method in Datatable to add each row to datatable. – tmk Mar 14 '17 at 07:08
  • Please post what you have tried based on that people can help you – Shrivallabh Mar 14 '17 at 07:13

1 Answers1

0

Just decalre the DataTable in global level earlier we were creating a new Data Table and loding the GridView now it will add new rows to Datatable and add to grid view

 DataTable dt = new DataTable();
 private void BindGrid()
 {
   string constring = @"Data Source=.\SQL2005;Initial Catalog=Northwind;Integrated Security=true";
   using (SqlConnection con = new SqlConnection(constring))
      {
        using (SqlCommand cmd = new SqlCommand("SELECT CustomerId, ContactName, Country FROM Customers", con))
          {
             cmd.CommandType = CommandType.Text;
             con.Open();
             dt.Load(cmd.ExecuteReader());
             dataGridView1.DataSource = dt;
             con.Close();
           }
       }
  }
Ravi Kanth
  • 1,182
  • 13
  • 38
  • @tmk has it worked for you if its worked then mark it as answer and do a upvote so that it will be helpful for other users. – Ravi Kanth Mar 15 '17 at 07:22