Friends
I had a datagridview in my windowsdesktop application to insert data into the database. when i click the add button validation should be done to ensure that no cells are left empty .I am not using cellvalidatorevent since i think its complicating process
i had written code like this
public void validateDatagrid()
{
if (tblpurchaserequest.RowCount == 1)
{
lblstatus.Text = "There is No Purchase Data to Add";
}
else
{
for (int i = 0; i < tblpurchaserequest.RowCount; i++)
{
if (tblpurchaserequest.Rows[i].Cells[0].Value.ToString().Trim() == "" || tblpurchaserequest.Rows[i].Cells[1].Value == null)
{
lblstatus.Text = "Please Enter Item in " + i + "th ROW";
}
if (tblpurchaserequest.Rows[i].Cells[0].Value.ToString().Trim() == "" || tblpurchaserequest.Rows[i].Cells[2].Value == null)
{
lblstatus.Text = "Please Enter Description in " + i + "th ROW";
}
if (tblpurchaserequest.Rows[i].Cells[0].Value.ToString().Trim() == "" || tblpurchaserequest.Rows[i].Cells[3].Value == null)
{
lblstatus.Text = "Please Enter Supplier in " + i + "th ROW";
}
if (tblpurchaserequest.Rows[i].Cells[0].Value.ToString().Trim() == "" || tblpurchaserequest.Rows[i].Cells[4].Value == null)
{
lblstatus.Text = "Please EnterQuantity in " + i + "th ROW";
}
}
}
}
but this is giving exception
Object reference not set to an instance of an object.
pls advice me my mistake
Obviously some value is null and the way you do the check in your if clause would need to be in a different order.
Change from:
to:
That is, check for NULL first. This will ensure that the second part in your if does not get evaluated, if the first part indeed returns a null (which is giving you an “object reference blah blah” error)
You will need to reverse the order on all if statements in your code block.