如何设置“;不可用”;DataGridView中null值的单词

本文关键字:DataGridView null 单词 何设置 设置 | 更新日期: 2023-09-27 18:12:04

我有一个employees表,其中第一个数字设置为not null,第二个数字可以是**null*,所以当我调用employees信息以查看它们在DataGridView中的信息时,空值显示为空单元格,但我想显示"不可用"字而不是空单元格,所以我该如何做到这一点?

如何设置“;不可用”;DataGridView中null值的单词

您可以使用以下任一选项:

  1. 设置列的DefaultCellStyleNullValue属性。它设置与DBNull.Valuenull的单元格值相对应的单元格显示值
  2. 当单元格值为DBNull.Valuenull时,使用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"));