搜索datagridview不工作 - System.NullReferenceException错误 [英] Search through datagridview not working - System.NullReferenceException error
本文介绍了搜索datagridview不工作 - System.NullReferenceException错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图通过我的datagridview上的第2列(数据类型:数字)运行搜索,但是不断收到以下错误消息:
I am trying to run a search through column 2 (data type: number) on my datagridview but keep getting the following error message:
An unhandled exception of type 'System.NullReferenceException' occurred in SpeedyRent.exe
Additional information: Object reference not set to an instance of an object.
如果(!string.Equals(row。单元格[1] .Value.ToString(),driverNo.Text,StringComparison.OrdinalIgnoreCase))
The error is being thrown at if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
我做错了什么?我已经包括我的代码:
What is it that I'm doing wrong? I've included my code below:
void driverSearch()
{
CurrencyManager manager = (CurrencyManager)BindingContext[dataGridView1.DataSource];
manager.SuspendBinding();
bool shouldNotFilter = string.IsNullOrEmpty(driverNo.Text);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if (shouldNotFilter)
{
row.Visible = true;
}
else
{
if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
{
row.Visible = false;
}
else
{
row.Visible = true;
}
}
}
manager.ResumeBinding();
}
private void driverNo_KeyUp(object sender, KeyEventArgs e)
{
driverSearch();
}
private void driverNo_TextChanged(object sender, EventArgs e)
{
driverSearch();
}
private void driverNo_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
driverSearch();
}
推荐答案
在foreach循环中尝试此块:
try this block in foreach loop:
if (shouldNotFilter)
{
row.Visible = true;
}
else
{
if(row.Cells[1].Value == null)
{
row.Visible = false;
}
else
{
if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
{
row.Visible = false;
}
else
{
row.Visible = true;
}
}
}
这篇关于搜索datagridview不工作 - System.NullReferenceException错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文