0

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);
        }
    }
  • move this `DataGridViewRow row = (DataGridViewRow)obj.Rows[0].Clone();` inside of the `while`. – Gusman May 27 '18 at 02:19
  • Possible duplicate of [Binding sqldatareader to gridview c#](https://stackoverflow.com/questions/16381490/binding-sqldatareader-to-gridview-c-sharp) – Chetan May 27 '18 at 02:56
  • 1
    Why not use a DataAdapter to fill a DataTable instead of using a Reader? From your code, you are not doing any processing of each row's data. – user3248578 May 27 '18 at 03:18
  • You try to add the same row each time, which is not allowed. So you need to create a new one for each reader.read, maybe by clone as Gusman suggests or simply by `int ix = obj.Rows.Add(1);` and then filling the fields... – TaW May 27 '18 at 08:12
  • @TruthSeeker I already try it but not work. – Deepal Nanayakkara May 28 '18 at 00:21
  • @Gusman Thank you Gusman. Your idea worked. – Deepal Nanayakkara May 28 '18 at 00:23

0 Answers0