【问题标题】:Display Null if datagridview Column is empty如果 datagridview 列为空,则显示 Null
【发布时间】:2015-05-07 18:35:26
【问题描述】:

我有一个带有几个列单元格的网格视图。我想要的只是检查一个空单元格并默认写入 null 。如果某些列未填充。,我想要一个默认的空文本到被省略的特定单元格

我试图创建这样的东西,但它不起作用,因为我不知道如何进一步发展

          private void Gridview_Output_CellFormatting_1(object sender, DataGridViewCellFormattingEventArgs e)
         { 
            string _Car = string.Empty;
            string _Dealer = string.Empty;
            string _Model = string.Empty;
            int gridcount = Gridview.Rows.Count;
            for (int i = 0; i < gridcount; i++)
            {
                _Car = "";
                _Dealer = "";
                _Model = "";

                if (Gridview.Rows[i].Cells[1].Value == DBNull.Value)
                {
                    _Car = "Null";
                }
                else
                {
                    _Car = Gridview.Rows[i].Cells[1].Value.ToString();
                }
                if (Gridview.Rows[i].Cells[2].Value == DBNull.Value)
                {
                    _Dealer = "Null";
                }
                else
                {
                    _Dealer = Gridview.Rows[i].Cells[2].Value.ToString();
                }
                if (Gridview.Rows[i].Cells[4].Value == DBNull.Value)
                {
                    _Model = "Null";
                }
                else
                {
                    _Model = Gridview.Rows[i].Cells[4].Value.ToString();
                }
            }
        }

【问题讨论】:

  • 你能包含你的gridview的标记吗?
  • mybad,我还以为是网页表单。
  • 好的。我该怎么做或让它发挥作用?

标签: c# winforms datagridview


【解决方案1】:
        foreach (DataGridViewRow dr in dataGridView1.Rows)
        {
            if (!dr.IsNewRow)
            {
                for (int c = 0; c <= dr.Cells.Count - 1; c++)
                {
                    if (dr.Cells[c].Value == null)
                    {
                        dr.Cells[c].Value = "NULL TEXT";
                    }
                }
            }
        }

【讨论】:

  • 它没有到达这一行 dr.Cells[c].Value = "NULL TEXT";我有三列,我希望它遍历所有这些索引。字符串 _Car = dr[1].ToString();字符串 _Dealer = dr[2].ToString(); string _Model = dr[4].ToString();
【解决方案2】:

您正在寻找DataGridViewCellFormatting 事件。 试试这样的:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (string.IsNullOrEmpty(e.Value as string))
    {
        e.Value = "NULL";
        e.FormattingApplied = true;
    }
}

如有必要,您还可以使用e.ColumnIndex 属性添加列条件。

【讨论】:

  • 我试过了,但它不起作用。你能检查我更新的代码吗
  • 你一定是新开发者?为每个 datagridview 单元格调用 CellFormatting。因此,您只需将我的回答中的string.IsNullOrEmpty(e.Value as string) 替换为e.Value == DbNull.Value 或任何对您而言有意义的东西。
  • 是的,我是新开发人员,很高兴认识像您这样有技能并愿意分享知识的人。我这样做了,它显示为未格式化。无效参数
  • if(e.Value == DBNull.Value) { e.Value = "NULL"; e.FormattingApplied = true; }
  • 您是否尝试使用我发布的确切代码,没有任何修改?
猜你喜欢
  • 1970-01-01
  • 2023-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-28
  • 1970-01-01
  • 2017-10-07
  • 2016-03-08
相关资源
最近更新 更多