2012-06-26 41 views
0

我想要引用DataGrid的特定列並將所有值獲取到數組中。我沒有得到任何錯誤,但問題是隻有數組的第零個位置似乎有一個值,而其他位置爲空。Datagrid中有4條記錄。我在做什麼錯查找特定的列,並在Visual C#中獲取數組值#

這裏是我的代碼:

private void button1_Click(object sender, EventArgs e) 
    { 
     string[] arr = new string[10]; 

     DataTable getdata = new DataTable(); 
     foreach (DataGridViewRow row in this.dataGridView1.Rows) 
     { 
      DataGridViewCell cell = row.Cells[1]; 
      { 
       if (cell != null && (cell.Value != null)) 
       { 
        for (int i = 0; i < dataGridView1.Rows.Count; i++) 
        { 
         arr[i] = cell.Value.ToString(); 
        } 
       } 
      } 
     } 

     if (arr[0] != null) 
     { 
      textBox3.Text = arr[0].ToString();//Prints value 
     } 
     else if (arr[1] != null)//Seems to be null 
     { 
      textBox2.Text = arr[1].ToString(); 
     } 
    } 
+0

您正在遍歷行兩次,一次在foreach中,一次在 –

+0

中應該如何更改 –

回答

1

試試這個:

private void button1_Click(object sender, EventArgs e) 
{ 
    string[] arr = new string[10]; 
    int i = 0; 

    DataTable getdata = new DataTable(); 
    foreach (DataGridViewRow row in this.dataGridView1.Rows) 
    { 
     DataGridViewCell cell = row.Cells[1]; 
     { 
      if (cell != null && (cell.Value != null)) 
      { 
       arr[i] = cell.Value.ToString(); 
      } 
      i++; 
     } 
    } 

希望這有助於。 - Corix

1

嘗試一些喜歡這個代替

private void button1_Click(object sender, EventArgs e) 
{ 
     List<String> columnValues = new List<String> 

     foreach (DataGridViewRow row in this.dataGridView1.Rows) 
     { 
      DataGridViewCell cell = row.Cells[1]; 
      { 
       if (cell != null && (cell.Value != null)) 
       { 
        columValues.Add(cell.Value.ToString()); 
        if (columnValues.Count == 2) 
        { 
         break; 
        } 
       } 
      } 
     } 

     if (columnValues.Count > 0) 
     { 
      if (columnValues.Count < 2) 
      { 
      textBox3.Text = columnValues[0];//Prints value 
      } 
      else 
      { 
       textBox2.Text = columnValues[1]; 
      } 
     } 
    } 

不喜歡的陣列。超過11個非空值的東西會崩潰。 不知道該數據表的用途是什麼。 如果您只將非空值置於集合中,爲什麼檢查它們是否爲空。 String.ToString()似乎有點毫無意義。

由於您只對2個非空值感興趣,因此增加了休息時間。 並且擺脫了最後一點邏輯,儘管我無法想出它背後的推理。

+0

謝謝您現在的作品:) –

相關問題