present sql query in data grid view c#

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • eranby
    New Member
    • Aug 2007
    • 17

    present sql query in data grid view c#

    hi,

    I'm using access db in my c# program I have a select query and I want to present
    the result in data grid view ,I succeed doing that with this while loop

    Code: ( c )
    int i = 0,j=0;
    while (dbReader.Read( ))
    {
    dataGridView2.R ows.Add();
    dataGridView2[j, dataGridView2.R ows.Count - 1].Value = (string) [ dbReader.GetVal ue(0).ToString( ); j++;
    dataGridView2[j, dataGridView2.R ows.Count - 1].Value = (string)dbReade r.GetValue(1); j++;
    dataGridView2[j, dataGridView2.R ows.Count - 1].Value = (string)dbReade r.GetValue(2);
    i++;
    j = 0;
    }

    is there an appropriate way doing it that sent the all result to the table at once?
    thanks,
  • balabaster
    Recognized Expert Contributor
    • Mar 2007
    • 798

    #2
    You haven't specified what DataGridView is - I'm assuming that it's a GridView object. In which case you can just set the DataSource property to your DataReader

    Code:
    Dim oCmd As New SqlCommand("Select....", oCon)
    Dim oRdr As SqlDataReader = oCmd.ExecuteReader()
    DataGridView2.DataSource = oRdr
    DataGridView2.DataBind
    oCmd.Dispose()
    This should do the job for you without making you iterate through every row in your data reader.

    [Edit: Oops, overlooked the fact that you said C#, sorry]
    C#
    Code:
    SqlCommand oCmd = New SqlCommand("Select...", oCon);
    SqlDataReader oRdr = oCmd.ExecuteReader();
    DataGridView2.DataSource = oRdr;
    DataGridView2.Databind();
    oCmd.Dispose();

    Comment

    • eranby
      New Member
      • Aug 2007
      • 17

      #3
      Originally posted by balabaster
      You haven't specified what DataGridView is - I'm assuming that it's a GridView object. In which case you can just set the DataSource property to your DataReader

      Code:
      Dim oCmd As New SqlCommand("Select....", oCon)
      Dim oRdr As SqlDataReader = oCmd.ExecuteReader()
      DataGridView2.DataSource = oRdr
      DataGridView2.DataBind
      oCmd.Dispose()
      This should do the job for you without making you iterate through every row in your data reader.

      [Edit: Oops, overlooked the fact that you said C#, sorry]
      C#
      Code:
      SqlCommand oCmd = New SqlCommand("Select...", oCon);
      SqlDataReader oRdr = oCmd.ExecuteReader();
      DataGridView2.DataSource = oRdr;
      DataGridView2.Databind();
      oCmd.Dispose();
      Hi,
      Thank you very much ,it was very helpful and solve my the problem!!

      Eran

      Comment

      Working...