我是C#的新手。我想将表的选定字段中的数据添加到DataGridView。我用过数据阅读器。执行时只添加一行。 while循环的第二次,错误发生为“提供的行已经属于DataGridView控件”。我的代码。任何人都可以帮忙...
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);
}
}