2012-06-15 129 views
-1

我想检查datagridview中的“many”列是否为空。C#检查datagridview列是否为空

这里我的代码

 for (int i = 0; i < (gridx.Rows.Count - 1); i++) 
     { 
      col = gridx.Rows[i].Cells["code"].Value.ToString(); 
      col4 = gridx.Rows[i].Cells["many"].Value.ToString();     
     } 

     if (col4 == "") 
     { 
      MessageBox.Show("Many is empty"); 
      this.Focus(); 
      return; 
     } 
     else 
     { 
      //my code in here 
     } 

,但它没有显示错误 “很多是空的”

前请

感谢
+0

当您逐步进行调试时,'col4'的值是多少? – Dave

+0

你想知道一个单元是空的还是全部单元?你有没有例外,你使用过调试器吗? –

回答

5

由于您将最后一个单元格的值分配给for循环中的col4,因此可以根据null对其进行检查。

for (int i = 0; i < (gridx.Rows.Count - 1); i++) 
     { 
      col = gridx.Rows[i].Cells["code"].Value.ToString(); 
      if(gridxRows[i].Cells["many"].Value == null ||  
       gridxRows[i].Cells["many"].Value == string.Empty) 
      { 
       col4 = gridx.Rows[i].Cells["many"].Value.ToString(); 
      } 
     } 

您当前的代码只会检查cell["many"]的最后一行是否为空。如果你想确保所有的列都是空的,那么你可以尝试下面的方法。

bool isColumnEmpty = true; 
for (int i = 0; i < (gridx.Rows.Count - 1); i++) 
     { 
      col = gridx.Rows[i].Cells["code"].Value.ToString(); 
      if(gridxRows[i].Cells["many"].Value == null ||  
       gridxRows[i].Cells["many"].Value == string.Empty) 
      { 
       col4 = gridx.Rows[i].Cells["many"].Value.ToString(); 
       isColumnEmpty = false; // that means some thing is found against cell 
      } 
     } 

现在检查isColumnEmpty标志是否已设置;

if(isCoulmnEmpty) 
{ 
      MessageBox.Show("Many is empty"); 
      this.Focus(); 
      return; 
} 
+0

'String.Empty'为我工作!谢谢! 'selectedRow.Cells [“Name_Of_Column”]。Value.ToString()== String.Empty' – Vbp

1

试试这个帮助我..和。

if(gridx.Rows[i].Cells["code"].Value == null) 
{ 
// do something here... 
} 

问候, Sharmila

0

如果使用databinding填充datagrid,我建议要“问”大约值(或更好的情况下),你的搜索数据。

如果您正在搜索的用户界面,并在这种情况下,根据您的文章,如果永远都不会跑,我看到两个选项:

  • 一定的价值,所以它不是空
  • 或值不是""(空字符串),但是null。要对此进行检查,它足以这样写:

if (col4 == null)

只是suggession:使用Visual Studio强大的调试工具,并会在几分钟内找出答案自己。

祝你好运。