C# 在CellFormatting事件中设置CellStyle会在鼠标悬停时引发异常
我有一张关于以下事件的表格。但是,当鼠标指针悬停在已设置了C# 在CellFormatting事件中设置CellStyle会在鼠标悬停时引发异常,c#,winforms,datagridview,C#,Winforms,Datagridview,我有一张关于以下事件的表格。但是,当鼠标指针悬停在已设置了CellStyle的单元格上时,应用程序会引发异常 DataGridViewCellStyle AStyle = new DataGridViewCellStyle { BackColor = Color.Green }; private void DGV_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (string.IsNul
CellStyle
的单元格上时,应用程序会引发异常
DataGridViewCellStyle AStyle = new DataGridViewCellStyle { BackColor = Color.Green };
private void DGV_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (string.IsNullOrEmpty(e.Value.ToString()))
{
e.CellStyle = AStyle;
}
例外情况:
base.OnMouseMove(e);
$exception{“值不能为空。\r\n参数名称:font“}System.ArgumentNullException
例外情况基本上是告诉您,
DataGridViewCellStyle
的Font
属性在用于设置CellStyle
时不能为空。将AStyle
变量的初始化方式更改为:
DataGridViewCellStyle AStyle;
public Form1()
{
InitializeComponent();
AStyle = new DataGridViewCellStyle { BackColor = Color.Green, Font = DGV.Font };
}
或者,您可以完全删除AStyle
(如果您只使用它来设置背景色),并使用如下内容:
e.CellStyle.BackColor = Color.Green;
还要注意的是,如果e.Value
为null,则e.Value.ToString()
可能会引发NullReferenceException。你可以考虑添加一个以避免这个:
if (string.IsNullOrEmpty(e.Value?.ToString()))
{
e.CellStyle = AStyle;
}
我了解到
cell.Style=AStyle
比cell.Style.Attribute=…
更可取,因为后者每次分配时都会创建一个新的DataGridViewCellStyle实例。因此,我对CellStyle
采用了相同的模式。在RowsAdded
事件中设置Cell.Style
时,它不需要Font
。@ca9163d9我不知道这是不是真的(因为它是一个可变类,我不认为每次都要克隆它有什么好的理由)。但是,如果您查看这些示例,您会发现它们也使用了e.CellStyle.SomeProperty
。也就是说,如果您不确定,您仍然可以使用AStyle
变量,如答案的第一个代码块所示;只需确保设置了所有必需的属性(因为您正在初始化一个新实例,而不是修改一个现有实例)