如何设置“;不可用”;DataGridView中null值的单词
本文关键字:DataGridView null 单词 何设置 设置 | 更新日期: 2023-09-27 18:12:04
我有一个employees
表,其中第一个数字设置为not null,第二个数字可以是**null*,所以当我调用employees
信息以查看它们在DataGridView
中的信息时,空值显示为空单元格,但我想显示"不可用"字而不是空单元格,所以我该如何做到这一点?
您可以使用以下任一选项:
- 设置列的
DefaultCellStyle
的NullValue
属性。它设置与DBNull.Value
或null
的单元格值相对应的单元格显示值 - 当单元格值为
DBNull.Value
或null
时,使用CellFormatting
事件并设置e.Value
示例1
this.dataGridView1.Columns[1].DefaultCellStyle.NullValue = "Unavailable";
示例2
void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex < 0 || e.RowIndex < 0)
return;
if (e.Value == DBNull.Value || e.Vallue == null)
e.Value = "Unavailable";
}
将Select
语句更改为类似的语句(使用CASE WHEN
(:
SELECT Id, CASE WHEN SecondNumber IS NULL THEN 'Unavailable' ELSE SecondNumber END AS SecondNumber
FROM yourTable
此解决方案还将包括一个扩展方法,因此请制作以下扩展方法。
这就是我们需要以更干净的方式设置网格值的地方(尽管是可选的(
public static void ApplyAction<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var entity in source)
{
action(entity);
}
}
现在你所要做的就是:
dataGridView1.Rows.OfType<DataGridViewRow>().Where(c => c.Cells[ColumnName.Index].Value == null).ApplyAction(new Action<DataGridViewRow>(c => c.Cells[ColumnName.Index].Value = "Unavailable"));