-1

I'm working for a new project my problem is i stop working in programming 2 months ago, so I'm back again with this problem.

private void LoadData()
{
    con.dataGet("Select * from [User]");
    DataTable dt = new DataTable();
    con.sda.Fill(dt);
    foreach(DataRow row in dt.Rows)
    {
        int n = dataGridView1.Rows.Add(); //Errors here
        dataGridView1.Rows[n].Cells["dgSno"].Value = n +1; //Not part of my database
        dataGridView1.Rows[n].Cells["dgName"].Value = row["Name"].ToString();
        dataGridView1.Rows[n].Cells["dgDob"].Value = Convert.ToDateTime(row["Dob"].ToString()).ToString("ddd/mm/yy");
        dataGridView1.Rows[n].Cells["dgEmail"].Value = row["Email"].ToString();
        dataGridView1.Rows[n].Cells["dgUserName"].Value = row["UserName"].ToString();
        dataGridView1.Rows[n].Cells["dgRole"].Value = row["Role"].ToString();
        dataGridView1.Rows[n].Cells["dgAddress"].Value = row["Address"].ToString();
    }
}

Error: An unhandled exception of type 'System.InvalidOperationException' occured in System.Windows.Forms.dll

Monica
  • 29
  • 4
  • 1
    dateGridView1.Rows.Add(row); – Ed Bangga Oct 16 '19 at 07:35
  • 1
    Possible duplicate of [Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound](https://stackoverflow.com/questions/8708057/rows-cannot-be-programmatically-added-to-the-datagridviews-row-collection-when) – Guy Oct 16 '19 at 07:35
  • i have one column name that does not belong on database sql server that cell is dgSno – Monica Oct 16 '19 at 07:57

1 Answers1

0

You should directly act on the DataTable using NewRow, initialize it and next Add it:

var row = dt.NewRow();
// init row
dt.Rows.Add(row);