I'm new to C#. I want to add data in selected fields of a table to a DataGridView. I used data reader. When executing only add one row. Second time of the while loop, error occurred as "Row provided already belongs to a DataGridView control". here my code. Anyone can help please...
public static void fillGrd(ref DataGridView obj, string tbl, string fld="*", string cond = "")
{
try
{
obj.Rows.Add();
DataGridViewRow row = (DataGridViewRow)obj.Rows[0].Clone();
obj.Rows.Clear();
cond = (cond == "") ? cond : " where " + cond;
string qry = "select " + fld+ " from " + tbl + cond;
cmd.CommandText = qry;
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
int ri = 0;
while (dr.Read())
{
for (int i = 0; i < dr.FieldCount - 1; i++)
{
row.Cells[i].Value = dr.GetString(i);
}
obj.Rows.Insert(ri,row);
ri++;
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error occured!" + ex.Message);
}
}