如何在C#中为DataGridView列单元格设置默认值

3
在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的"In_Tim"列。这些数值只有当我点击特定单元格时才会显示出来,如何在所有列中填充默认值?


1
DefaultValuesNeeded 只有在点击新行时才会被使用 - "当用户进入新记录的行时发生,以便可以用默认值填充它。" - 因此它不会应用于列中的所有单元格。 - stuartd
好的,但是我应该使用什么来代替“DefaultValuesNeeded”来解决我的问题呢?@stuartd - Shiva Debrown
你需要展示从数据库中获取数值的代码。 - stuartd
2个回答

10

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

5
dataGridView1.Columns["in_time"].DefaultCellStyle.NullValue = "9 AM";
dataGridView1.Columns["Out_time"].DefaultCellStyle.NullValue = "6 PM";  

在一些建议之后,这是我想要在数据网格视图中展示的列:


3
这是空值,意味着当单元格的值为空时,它只会显示,而不是真正的默认值。 - Mojtaba Rezaeian
请不要这样做。对于未来的程序员来说,这非常令人困惑。他们需要查看你的代码并试图弄清楚为什么由于出现似乎非空的空值而导致 SQL 语句等无法运行。 - J. Rockwood

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接