如何在c#中设置datagridview列单元格的默认值

本文关键字:单元格 默认值 datagridview 设置 | 更新日期: 2023-09-27 18:25:51

如何在c#中为datagridview列单元格设置默认值,而有些列用数据库值填充,有些列用默认值填充,就像这样
例如,第1列、第2列、第3列由数据库值填充,其余列第4列单元格用上午9点填充,第5列用下午6点填充

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";
} 

我使用这段代码,但值在datagridview的行和列的末尾,并且在我单击特定单元格之前,这些值是不可见的
如何在所有列单元格中填充默认值?

如何在c#中设置datagridview列单元格的默认值

DataGridView控件有一个名为DefaultValuesNeeded的事件,用于处理新添加行的默认值填充。

MSDN关于此事件的文章

文章中概述的DefaultValuesNeeded事件的基本语法如下:

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();
}
dataGridView1.Columns["in_time"].DefaultCellStyle.NullValue = "9 AM";
dataGridView1.Columns["Out_time"].DefaultCellStyle.NullValue = "6 PM";  

经过一些建议这就是我想要在datagridview列

中显示的方式