2

c# windows forms i have a datagridview and two columns are present which are created at form design time. i fetch the data from a table and want to add the data row-wise into the grid.

i could do it in two ways

1. for every row in the table

DataGridView1.Rows.Add(row["EmpId"], row["Name"]);

2. using array - for every row in the table

   ArrayList grdrow = new ArrayList();
   grdrow.Add(0);
   grdrow.Add(row["EmpId"].ToString());
   grdrow.Add(row["Name"].ToString());
   DataGridView1.Rows.Add(grdrow.ToArray());

i want to add rows into the gridview using DataGridViewRow, but its not working. code i used is:

foreach (DataRow row in ds.Tables[0].Rows)
{
    DataGridViewRow rowadd = new DataGridViewRow();
    rowadd.CreateCells(DataGridView1); 
    rowadd.Cells["Empid"].Value = row["EmpId"]; // it gives error here Column name 'Empid' cannot be found
    rowadd.Cells["EmpName"].Value = row["Name"];
    DataGridView1.Rows.Add(row);
}
johnsonpinto
  • 61
  • 2
  • 9

1 Answers1

1

The below segment should work for you.

//set your count of columns here
dataGridView1.ColumnCount = 2;

// Assign your columns
dataGridView1.Columns[0].Name = "EmpId";
dataGridView1.Columns[1].Name = "Name";

// Add your rows here    
this.dataGridView1.Rows.Add("ValueForColl1", "ValueForColl2");

Should do the trick for you the issue, drop me a message if your unsure.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • how this is different from `DataGridView1.Rows.Add(row["EmpId"], row["Name"]);` from question?? – ASh Jan 31 '18 at 09:11