How to set default value to datagridview column cells in c#
Solution 1
The DataGridView control has an event called DefaultValuesNeeded which handles default value population for a newly added row.
MSDN article regarding this event
The basic syntax for the DefaultValuesNeeded event outlined within the article is as follows:
private void dataGridView1_DefaultValuesNeeded(object sender, System.Windows.Forms.DataGridViewRowEventArgs e)
{
e.Row.Cells["Region"].Value = "WA";
e.Row.Cells["City"].Value = "Redmond";
e.Row.Cells["PostalCode"].Value = "98052-6399";
e.Row.Cells["Country"].Value = "USA";
e.Row.Cells["CustomerID"].Value = NewCustomerId();
}
Solution 2
dataGridView1.Columns["in_time"].DefaultCellStyle.NullValue = "9 AM";
dataGridView1.Columns["Out_time"].DefaultCellStyle.NullValue = "6 PM";
after some suggestions This is how i wanted to show in datagridview columns
Related videos on Youtube
Shiva Debrown
Updated on March 12, 2020Comments
-
Shiva Debrown about 4 years
How to set default value to datagridview column cells in c# while some columns are are filled with database values and some columns to be filled with default values like this way..
For example 1st column,2nd column,3rd columns filled from database values and remaining columns 4th column cell to be filled with 9 AM and 5th column with 6 PMprivate void dataGridView1_DefaultValuesNeeded(object sender, DataGridViewRowEventArgs e) { // This is not working as I explain below e.Row.Cells["in_time"].Value = "9 AM"; e.Row.Cells["Out_time"].Value = "6 PM"; }
I use this code but the values are at the end of the row and column is "In_Tim" column of datagridview, and the values are invisible until I click on the particular cell..
How can I fill default values in all the column cells?-
stuartd over 9 yearsDefaultValuesNeeded is only used when clicking into a new row - "Occurs when the user enters the row for new records so that it can be populated with default values." - so it won't be applied to all cells in the column.
-
Shiva Debrown over 9 yearsOk ,But what shall I use instead of 'DefaultValuesNeeded' to solve My problem @stuartd
-
stuartd over 9 yearsYou need to show the code where you are populating the values from the database.
-
-
Mojtaba Rezaeian over 8 yearsThis is Null Value, means it is just shown when cell value is null and is not really the default value.
-
J. Rockwood about 2 yearsPlease don't do this. It is very confusing for future programmers looking at your code trying to figure out why SQL statements and such won't work due to null values that appear non null.