繁体   English   中英

CellLeave上的DataGridView单元格为null

[英]DataGridView cell is null on CellLeave

当我离开单元格时,我试图对单元格的内容进行一些文本处理。 我有以下代码,但是当我在单元格中输入任何文本然后离开时,我得到以下异常。

An unhandled exception of type 'System.NullReferenceException' occurred in Program.exe

Additional information: Object reference not set to an instance of an object.

如果我在上面断开和鼠标悬停.value它确实为空,但我已将数据输入到单元格中! 什么给出了什么?

private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 3)
    {
        string entry = "";
        MessageBox.Show(dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
        MakeTextFeet(entry);
    }
    if (e.ColumnIndex == 4)
    {
        string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();
        MakeTextFeet(entry);
    }
}

触发DataGridView CellLeave事件时,单元格的值处于瞬态状态。 这是因为DataGridView可能绑定到数据源,并且不会提交更改。

您最好的选择是使用CellValueChanged事件。

添加一些检查:

DataGridViewCell MyCell =  dataGridView1[e.ColumnIndex, e.RowIndex];

if (MyCell != null)
{
    if (MyCell.Value != null)
    {
    }
}

我想你想要处理CellEndEdit而不是CellLeave。

在CellLeave上,编辑的单元格的Value属性仍然保持不变(即,通过断开和检查Value观察到的空单元格为null)。 在CellEndEdit上,已设置其新值。

尝试这样的事情,其中​​我试图通常坚持你的原始代码:

private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
    DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];

    if (e.ColumnIndex == 3 || e.ColumnIndex == 4)
    {
        string entry = "";
        if (cell.Value != null)
        {
            entry = cell.Value.ToString();
        }
        MessageBox.Show(entry);
        MakeTextFeet(entry);
    }
}

我想你要留下一个空白区域并试图处理它的价值。

当您将保留以下代码的空白单元格值时:

string entry = dataGridView1[e.ColumnIndex, e.RowIndex].Value.ToString();

字符串条目中的值将是空格(entry =“”),当您通过将其传递给另一个函数[MakeTextFeet(entry);]进一步处理此值时,它会给您错误。

从我的角度来看这个问题的解决方案是>>>

将每行代码放在上面的方法中,MakeTextFeet(Entry)也在try块中。

当你写catch块时,将该块留空。 例如。

try
{
.
.
.
}
catch(Exception)
{
}

通过这件事你的异常自然会被抓住,但由于它的不可忽视,它不会告诉你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM