Search code examples
c#oledbdatareader

add row to datagridview while OleDbDataReader.read()


I use C# and WindowsForms.

I want to insert a record to database and then add too my gridview

I test the codebellow but it dosent work.

 //some codes here
 OleDbDataReader dr = dbCommand.ExecuteReader();
 while (dr.Read())
            {
            //DataGridViewRow row=new DataGridViewRow(); ????
            //Gview.Rows.AddNew(...) ???
            // what sould I write here??
            }

How can I do that??


Solution

  • Firstly you need to get the values out of your DataReader, then you need to assign them as a row. The simplest way is to add them as an object array: I've added a using statement to make sure the reader is correctly disposed of after use.

    // some codes here
    using (OleDbDataReader dr = dbCommand.ExecuteReader())
    { 
        while (dr.Read())
        {
            string f1 = dr.GetString("Field1");
            string f1 = dr.GetString("Field2");
            GView.Rows.Add(new object[] {f1, f2});
        }
    }