2015-08-18 39 views
0

當我搜索此問題時,我找不到任何內容,因爲我不知道如何將其寫入。在任何單元格中將字符串值與datagridview行0進行比較

我有一個從excel文件中獲取值的dataGridView。這工作正常,但我想比較行0中的所有值與字符串值。

這裏是我的代碼有

string mat = "test"; 
if(mat == dataGridView1[0,0].Value.ToString()) 
     { 
      tst.Text = dataGridView1[1,0].Value.ToString(); 
     } 

這僅適用於在第一項中的細胞。我需要掃描所有值。我會認爲它會是這樣的:

string mat = "test"; 
int x = ???; 
if(mat == dataGridView1[0,x].Value.ToString()) 
     { 
      tst.Text = dataGridView1[1,x].Value.ToString(); 
     } 

這讓我瘋狂,因爲它是如此簡單的事情,我知道必須是可能的。否則,我將不得不復制並粘貼x等於1,2,3等等,因爲表格中有很多值。

任何建議將不勝感激。

回答

1

你可以把你在一個循環

string mat = "test"; 
for(int i=0;i<dataGridView1.Rows[0].Cells.Count;i++){ 
     if(dataGridView1[0,i].Value != null && mat == dataGridView1[0,i].Value.ToString()) 
     { 
      tst.Text = dataGridView1[1,i].Value.ToString(); 
     } 
} 

我強烈remcommend您閱讀本article

+0

爲什麼你的循環下去,直到我<10 verrification? – varocarbas

+0

我只是拿了一個隨機數 – litelite

+0

爲什麼不使用實際變量(列數/單元格數)? – varocarbas

1
if(dataGridView1 != null) 
{ 
    foreach (DataGridViewCell cell in dataGridView1.Rows[0].Cells) 
    { 
     if (cell.Value != null && cell.Value.Equals("test")) 
     { 
      tst.Text = cell.Value; 
     } 
    } 
} 
+0

他說只爲第一行... – litelite

相關問題