我遇到这个问题已经有一段时间了。
我打算做的是,如果所有的 cell[0]
都有值,它将触发一个事件。如果有 null
,它会改变 TextBox
的值。
这是我的代码:
private void button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dataGridView1.Rows[i].Cells[0].Value.ToString() == null)
{
textbox.Text = "null";
break;
}
else
{
MessageBox.Show("No null");
}
}
但是这里发生的事情是,例如我在 DataGridView
中有 3 行,如果第一行不为空,它将午餐 MessageBox
。我希望当所有行的单元格都不为空时触发 MessageBox
。
最佳答案
使用 LINQ 和 Any
方法:
if (dataGridView1.Rows.Cast<DataGridViewRow>().Any(c => c.Cells[0].Value?.ToString() == null))
{
textbox.Text = "null";
}
else
{
MessageBox.Show("No null");
}
另外最好使用string.IsNullOrWhiteSpace
:
if (dataGridView1.Rows.Cast<DataGridViewRow>()
.Any(c => string.IsNullOrWhiteSpace(c.Cells[0].Value?.ToString())))
关于c# - 如何检查 DataGridView 中的所有行是否不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46205327/