2017-09-13 62 views
2

我有這個問題很久了。如何檢查DataGridView中的所有行是否都不爲空?

我打算做的是如果所有的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"); 
     } 
    } 

但是什麼在這裏發生的是,比如我有3行中DataGridView,如果第一行不是空它將午餐MessageBox。我希望MessageBox在所有行的單元不爲空時被觸發。

+0

哪裏是哪裏來的數據? –

回答

2

試試這個:

bool anyNull = false; 
for (int i = 0; i<dataGridView1.Rows.Count; i++) 
{ 
    if (dataGridView1.Rows[i].Cells[0].Value.ToString() == null) 
    { 
     textbox.Text = "null"; 
     anyNull = true; 
     break; 
    } 
} 

if (!anyNull) 
    MessageBox.Show(""); 
-1

你可以試試下面的代碼,但不建議使用goto

for (int i = 0; i < dataGridView1.Rows.Count; i++) 
    { 

     if (dataGridView1.Rows[i].Cells[0].Value.ToString() == null) 
     { 
      textbox.Text = "null"; 
      goto a; 
     } 

    } 

    a: MessageBox.Show("Null"); 
+2

goto ...... gross –

+1

xDDDDDDDDDDDDDDD – LONG

+1

爲什麼不使用'break'? – ainwood

0

試試這個:

for (int i = 0; i < dataGridView1.Rows.Count; i++) 
{ 
     if (dataGridView1.Rows[i].Cells[0].Value.ToString() == null) 
     { 
      textbox.Text = "null"; 
      break; 
     } 
} 
if(textbox.Text != "null") 
{ 
    MessageBox.Show("No null"); 
} 
5

使用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()))) 
+0

對我來說''c => c.Cells [0] .Value.ToString()'用'c => c.Cells [0] .Value修復了'System.NullReferenceException'的炸彈' –

+0

@ blaze_125或者使用* Null-conditional *('?.')這樣的運算符'string.IsNullOrWhiteSpace(c.Cells [0] .Value?.ToString())' –

相關問題