Thursday, July 21, 2011

Default Values via BindingSource's AddingNew Event

I new that BindingSource's AddingNew event can handle all default value assignment, but was so frustrated that I could not find any articles/tutorials which guided me on how to use it. Although MSDN had description, but it did not have samples on how to use it. However, with few long hour searches I came to a source which enlighted me on how to use this event.

A sample code looks like this:
 
private void branchBindingSource_AddingNew(object sender, AddingNewEventArgs e)
{

//// Get data table view 
DataView dataTableView = branchBindingSource.List as DataView;


//// Create row from view
DataRowView rowView = dataTableView.AddNew();


rowView["BranchID"] = -1;
rowView["BranchCode"] = "001";
rowView["BranchDescription"] = "002";

//// Set New row
e.NewObject = rowView;

branchBindingSource.MoveLast(); 

}