问题
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.
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();
}
回答1:
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;
}
}
}
来源:https://stackoverflow.com/questions/23154523/search-through-datagridview-not-working-system-nullreferenceexception-error