Reputation: 531
I have a Windows Forms application which contains a DataGridView inside it. The DataGridView gets populated from a DataSource which is a list of MyClass. MyClass contains a set of properties and a constructor like so:
public class MyClass
{
public PropertyA{get;set};
public ProppertyB{get;set;}
public ProppertyC{get;Set}
}
Then in the Main form I have a method which returns a List myCollection and a button which populates the DataGridView with "myCollection" like so:
private void btlLoadDataInDataGrid_Click(object sender, EventArgs e)
{
var headers = GetAllHeaders();//GetAllheaders returns a List<MyClass>
dataGridView1.DataSource = headers;
}
What I get is a DataGridView with the columns from the original MyClass. Now I want to be able to edit the data in the DataGridView and commit this change to the actual list of MyClass properties. Can somebody please advice what would be a best approach to do this?
Upvotes: 0
Views: 1362
Reputation: 3388
When you edit your grid whose DataSource
is set to a List of objects and change any cell's value, the underlying data in the row is automatically updated. In your case the underlying row data is of type MyClass
.
At any point of time you can get the updated row data, using the DataGridView.DataBoundItem
property.
Sample code:
foreach(DataGridViewRow item in dataGridView1.Rows)
{
MyClass rowData = item.DataBoundItem as MyClass;
if(rowData != null)
{
// Do your stuff
}
}
The data commit logic is different when your grid is populated from a database. You have to write code to commit the changed data to the database.
Upvotes: 2