DataGridView and new rows
-
I have a collection (IList) of custom objects bound to a DataGridView. When you click on the * line to create a new row the DataGridView automatically creates a new object for you to edit. When it does this it calls the default constructor. What I would like to do is intercept this process so that I can either call a different constructor or else do some extra initialization before the DataGridView tries to bind to it. Is there a way to do this? The RowsAdded and UserAddedRow event both fire too late. Which method is the DataGridView calling to create a new row? I don't think it's actually getting added to the collection until the user edits the row. Thanks
-
I have a collection (IList) of custom objects bound to a DataGridView. When you click on the * line to create a new row the DataGridView automatically creates a new object for you to edit. When it does this it calls the default constructor. What I would like to do is intercept this process so that I can either call a different constructor or else do some extra initialization before the DataGridView tries to bind to it. Is there a way to do this? The RowsAdded and UserAddedRow event both fire too late. Which method is the DataGridView calling to create a new row? I don't think it's actually getting added to the collection until the user edits the row. Thanks
One approach is to add a handler for the BindingSource's AddingNew event. E.g.:
InitializeGrid()
{
// Create sample List of custom objects. First object uses a non-default
// constructor, the second uses the default (no reason, just seemed
// like something to do in the example).
List<CustomItem> sourceList = new List<CustomItem>();
CustomItem firstItem = new CustomItem("Special content");
sourceList.Add(firstItem);
CustomItem nextItem = new CustomItem();
sourceList.Add(nextItem);// Create the BindingSource, add the list, and add an event handler // for the AddingNew event. BindingSource bindingSource = new BindingSource(); bindingSource.DataSource = sourceList; bindingSource.AddingNew += new AddingNewEventHandler(bindingSource\_AddingNew); // Bind to the DataGridView. dataGridView.DataSource = bindingSource;
}
private void bindingSource_AddingNew(object sender, AddingNewEventArgs e)
{
// Use non-default constructor for the new object that will
// be the source for the new row.
e.NewObject = new CustomItem("Not default content");
}An alternative is to use the DataGridView's DefaultValuesNeeded event, but the object has already been constructed by the time this event fires.