我正在尝试通过我的datagridview上的第2列(数据类型:数字)运行搜索,但不断收到以下错误消息:
An unhandled exception of type 'System.NullReferenceException' occurred in SpeedyRent.exe
Additional information: Object reference not set to an instance of an object.
错误发生在if (!string.Equals(row.Cells[1].Value.ToString(), driverNo.Text, StringComparison.OrdinalIgnoreCase))
我做错了什么?我在下面提供了我的代码:
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();
}
答案 0 :(得分:1)
在foreach循环中尝试此块:
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;
}
}
}