20 December 2013

Add the Row Programmatically to the DataGridView

Hi Friends,

Lets see how to add the row to the DataGridView if its already bind to DataSource. Remember if DataGridView is already bound with any DataSource, You can not directly add DataGridViewRow or DataRow to the DataGridView.

If you have bound the DataTable as DataSource with DataGridView, then you just need to add the row in DataTable it will automatically reflect in DataGridView. But sometime we face the problem we have List<object> of the object and we have DataGridView. Of course we can bind the List with DataGridView(Refer this link), but we can not add the row the DataGridView after binding the DataSource.  The best approach to overcome this problem is add the Object/Row in DataSource, your List <object> or DataTable.

1.  If you have bound the DataGridView with List<object>
     list = new List<MyClass>();
     list.Add(new MyClass("name1", "desc1", "path1"));  
     list.Add(new MyClass("name2", "desc2", "path2"));
     list.Add(new MyClass("name3", "desc3", "path3"));


     var bindingList = new BindingList<MyClass>(list);
     BindingSource bindingSource = new BindingSource(bindingList, null);
     dataGridView1.DataSource = bindingSource;
Now to add the row in grid you just need to add the object in the list and it will automatically reflect in DataGridView.
    ..
    ..
    // create the blank object
    MyClass obj = new MyClass("", "", "");

    //create the 5 blank lines in Grid
    for(int i=0; i <5; i++)
       list.Add(obj);
    ..
    ..

2.  If you have bound the DataGridView with the DataTable. You just need to add the row in DataTable as below-
    // Create new DataRow
    DataRow newCustomersRow = dt.NewRow();
 
    // add the column same as specified in DataTable and set the value
    newCustomersRow["Name"] = "";
    newCustomersRow["Description"] = "";
    newCustomersRow["Path"] = "";

    // add the row in DataTable which is bound as DataSource for Grid
    dt.Rows.Add(newCustomersRow);

Thanks..!!
Happy Knowledge sharing..!! :)

No comments:

Post a Comment