简体   繁体   中英

How to set default value to datagridview column cells in c#

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 PM

private 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?

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

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM