如何检查DataGridView中的所有行是否都不为空?

yuz*_*rui 2 c# for-loop datagridview winforms

我有这个问题很长一段时间.

我打算做的是,如果所有的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");
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是这里发生的事情是例如我有3行DataGridView,如果第一行不是null,它将在午餐时间MessageBox.我希望MessageBox在所有行的单元格都不为空时触发.

Sal*_*ari 5

使用LINQ和Any方法:

if (dataGridView1.Rows.Cast<DataGridViewRow>().Any(c => c.Cells[0].Value?.ToString() == null))
{
    textbox.Text = "null";
}
else 
{
    MessageBox.Show("No null"); 
}
Run Code Online (Sandbox Code Playgroud)

另外最好使用string.IsNullOrWhiteSpace:

if (dataGridView1.Rows.Cast<DataGridViewRow>()
     .Any(c => string.IsNullOrWhiteSpace(c.Cells[0].Value?.ToString())))
Run Code Online (Sandbox Code Playgroud)