Mayank Jani

Mayank Jani

  • 1.4k
  • 477
  • 29.4k

Code for Add and/or Append a row in GridView C#

Jun 29 2018 8:35 AM
Hii members,
 
In my application's form there is a DropDownList and a DataGridView. I select items from the DDL and the same adds into DGV and I save it to the DB. Later, if I want to edit the DVG list, I need to delete some items and add some items or just add to existing items. When I try to do this, the system show error, 'Object reference not set to an instance of an object.'
 
Here is my code...
 
if (dgvAdvice.Rows.Count > 0)
{
DataTable dt = dgvAdvice.DataSource as DataTable;
dt.Rows.Add(cmbAdvice.SelectedText);

dgvAdvice.Columns[0].Width = 300;
}
else
{
dgvAdvice.ColumnCount = 1;
dgvAdvice.Rows.Add(cmbAdvice.Text);

dgvAdvice.Columns[0].Width = 300;
 
I want to add code in DDL's Key_Up event like this...
If the row (already) exists then append else (consider as new and) add row(s).
 
Please note that if there is already rows exist in DGV, I can append rows and save IN EDIT MODE but, If I add new row in edit mode only one row adds and when try to add second row, it shows the error mentioned above.
 
Also note that I work in C# Windows Application with MS Access as db.
 
Thanks
 
Mayank Jani.

Answers (2)