gpt4 book ai didi

c# - 在 DataGridView 中搜索数据时出现 NullReferenceException

转载 作者:行者123 更新时间:2023-11-30 22:15:49 24 4
gpt4 key购买 nike

您好,我编写了这段代码来在 gridview 中搜索 carserial。但是我得到一个错误:

"Object reference not set to an instance of an object."

foreach (DataGridViewRow row in dataGridView2.Rows)
{
if (row.Cells["CardSerial"].Value.ToString().Equals(textBox2.Text))
{
dataGridView2.Rows[row.Index].DefaultCellStyle.BackColor = Color.Yellow;
}
}

你能告诉我问题是什么吗?

最佳答案

最有可能的是,以下项为 null,这会在您取消引用它时导致异常:

  • dataGridView2
  • row.Cells["CardSerial"]
  • row.Cells["CardSerial"].Value
  • textBox2
  • dataGridView2.Rows[row.Index]
  • dataGridView2.Rows[row.Index].DefaultCellStyle

要找出是哪一个,请调试您的程序,并使用监 window 口、即时窗口或添加一些调试/跟踪输出行。

需要特别注意的是 row.Cells["CardSerial"].Value 为 null 的情况。

关于c# - 在 DataGridView 中搜索数据时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17780521/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com