友 我在windowsdesktop应用程序中有一个datagridview,用于将数据插入数据库。当我点击添加按钮时,应该进行验证以确保没有单元格留空。我不使用cellvalidatorevent因为我认为它的复杂过程 我写过像这样的代码
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";
}
}
}
}
但这是例外 你调用的对象是空的。 请告诉我我的错误
答案 0 :(得分:1)
显然有些值为null,你在if子句中进行检查的方式需要采用不同的顺序。
更改自:
if (tblpurchaserequest.Rows[i].Cells[0].Value.ToString().Trim() == ""
|| tblpurchaserequest.Rows[i].Cells[1].Value == null)
为:
if (tblpurchaserequest.Rows[i].Cells[1].Value == null
|| tblpurchaserequest.Rows[i].Cells[0].Value.ToString().Trim() == "")
即,首先检查NULL。这将确保if中的第二部分不会被评估,如果第一部分确实返回null(这会给你一个“对象引用blah blah”错误)
您需要撤消代码块中所有if语句的顺序。
答案 1 :(得分:0)
编写一个方法,例如:
private void CallingMethod()
{
DataGridView dgv = new DataGridView();
if (IsNullOrEmpty(dgv.Rows[0].Cells[0].Value)
{
lblValue.Text = "Please enter a value for this cell";
}
}
// Method to check if the cell is empty
public bool IsNullOrEmpty(object cellValue)
{
if (cellValue == null)
{
return true;
}
else
{
if (cellValue.ToString().Trim() == "")
{
return true;
}
}
return false;
}
这应该简化您的代码并使其更易于阅读和理解。
对象引用错误的原因是因为如果对具有null值的对象使用.ToString(),则会引发异常。我的建议是首先检查值是否为null,如果不是,则测试它是否为空字符串。