我正在检查所选行的单元格7,8,9是否为空。但是,即使所有单元格的值都为空,它也只显示“已启用”。这是我的代码
private void btnTest_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvReceivingproducts.Rows)
{
if (row.Cells[7].Value != null && row.Cells[8].Value != null && row.Cells[9].Value != null)
{
lblchecker.Text = "enabled";
}
else
{
lblchecker.Text = "disabled";
}
}
}
答案 0 :(得分:1)
此代码中可能存在两个错误:
1。上面所有答案都提到了一个
2。 你是否意识到lblchecker.Text将只有一个对应于GridView中最后一行的值?(你的逻辑似乎不正确,你是否试图为每一行设置一个值?因为现在这是而不是代码导致的结果。)
一些好的做法建议:
1。避免使用索引。如果您稍后重新排列列怎么办?请尝试使用列名称
2。更好的方法是使用DataKeys
3。如果预先计算这个“启用”/“禁用”值,即在数据绑定之前,甚至更好的方法。可能是您可以在SQL或业务层中执行此操作。这取决于这个
<强>更新强>
如果在每行中设置值,则可以指示每行“已启用”值。使用您的代码,可能的方法可能是这样的:
private void btnTest_Click_1(object sender, EventArgs e)
{
foreach (DataGridViewRow row in dgvReceivingproducts.Rows)
{
if (row.Cells[7].Value != null && row.Cells[8].Value != null && row.Cells[9].Value != null)
{
row.Cells[X].Value = "enabled";
}
else
{
row.Cells[X].Value = "disabled";
}
}
}
答案 1 :(得分:0)
您是否尝试过使用Convert.IsDBNull()
代替!=null
答案 2 :(得分:0)
你可以试试这个::
if ((row.Cells[7].Value != null && row.Cells[8].Value != null && row.Cells[9].Value != null)
|| (row.Cells[7].Value != DBNull.Value && row.Cells[8].Value != DBNull.Value && row.Cells[9].Value != DBNull.Value))
{
lblchecker.Text = "enabled";
}
else
{
lblchecker.Text = "disabled";
}
如果不起作用,请使用IsNullOrWhitespace函数进行测试:
String.IsNullOrWhitespace(row.Cells[8].Value... )