DataGridView - Set Default values for New Row

Posted by VIJI Saturday, July 4, 2009

We may want to populate the default values for cells in new row of DataGridView. This feature reduces the time of data entry especially if the DataGridView contains more number of columns.


This feature can be accomplished using DefaultValuesNeeded event of DataGridView.

Whenever the new row is selected for entering data, DataGridView throws DefaultValuesNeeded Event.


We need to implement handle this event. That is we have to set the default values for each cell in the New Row.


Example




private void PopulateGridView()
{

//Create a DataTable instance

DataTable dt = new DataTable();

//Create Sevent columns
DataColumn col1 = new DataColumn("CustID");
DataColumn col2 = new DataColumn("First Name");
DataColumn col3 = new DataColumn("Last Name");
DataColumn col4 = new DataColumn("Country");
DataColumn col5 = new DataColumn("State");
DataColumn col6 = new DataColumn("City");
DataColumn col7 = new DataColumn("ZIPCode");


//Define data type of the columns

col1.DataType = System.Type.GetType("System.Int");
col2.DataType = System.Type.GetType("System.String");
col3.DataType = System.Type.GetType("System.String");
col4.DataType = System.Type.GetType("System.String");
col5.DataType = System.Type.GetType("System.String");
col6.DataType = System.Type.GetType("System.String");
col7.DataType = System.Type.GetType("System.String");



//Add these columns to the Data Table

dt.Columns.Add(col1);
dt.Columns.Add(col2);
dt.Columns.Add(col3);
dt.Columns.Add(col4);
dt.Columns.Add(col5);
dt.Columns.Add(col6);
dt.Columns.Add(col7);

//Create Rows in the DataTable table

DataRow row = dt.NewRow();

Fill All Columns with Data

row[col1] = 1100;
row[col2] = "Viji";
row[col3] = "Rajkumar";
row[col4] = "USA";
row[col5] = "Ohio";
row[col6] = "Mentor";
row[col7] = "44074";


//Add the Row into DataTable

dt.Rows.Add(row);

//Bind it to DataGridView

this.dbGridView.DataSource = dt;

}


//Populate the default values
private void dbGridView_DefaultValuesNeeded(object sender,
DataGridViewRowEventArgs e)
{
//Populate default values for country, city, state and ZipCode
e.Row.Cells["First Name"].Value = " ";
e.Row.Cells["Last Name"].Value = " ";
e.Row.Cells["Country"].Value = "USA";
e.Row.Cells["State"].Value = "Ohio";
e.Row.Cells["City"].Value = "Mentor";
e.Row.Cells["ZIPCode"].Value "44074";
e.Row.Cells["CustomerID"].Value = NewCustomerId();
}



Whenever we select the new row, the default values will get filled into the cells of new row of data gridview.

0 Responses to DataGridView - Set Default values for New Row

Post a Comment