2011-04-07 209 views
5

我正在用c#構建一個程序,並在其中包含了一個datagridview組件。 datagridview具有固定數量的列(2),我想將它們保存到兩個單獨的數組中。行數量確實發生了變化。我怎麼能這樣做?將C#datagridview列轉換爲數組

回答

3

試試這個:

ArrayList col1Items = new ArrayList(); 
ArrayList col2Items = new ArrayList(); 

foreach(DataGridViewRow dr in dgv_Data.Rows) 
{ 
    col1Items.Add(dr.Cells[0].Value); 
    col2Items.Add(dr.Cells[1].Value); 
} 
+0

在使用Jay的代碼時,第一次得到錯誤之後,我試了一下 - 它確實有效。但是,如果你說傑伊的效率更高,我可能會繼續試驗! – Xedfire 2011-04-07 21:49:32

11

假設一個名爲dataGridView1的DataGridView,你想前兩列的內容複製到字符串數組,你可以這樣做:

string[] column0Array = new string[dataGridView1.Rows.Count]; 
string[] column1Array = new string[dataGridView1.Rows.Count]; 

int i = 0; 
foreach (DataGridViewRow row in dataGridView1.Rows) { 
    column0Array[i] = row.Cells[0].Value != null ? row.Cells[0].Value.ToString() : string.Empty; 
    column1Array[i] = row.Cells[1].Value != null ? row.Cells[1].Value.ToString() : string.Empty; 
    i++; 
} 
+0

+1,可能稍微更有效。 – 2011-04-07 18:34:26

+0

@Abe當然,如果他使用的是.NET 2.0+,我們建議使用List 而不是Array或ArrayList。 – 2011-04-07 18:40:23

+0

對我而言,確實如此,但我的印象是,如果您事先知道集合的長度,通常使用陣列更好/更高效(儘管性能增益可能不明顯)。 – 2011-04-07 18:47:28

3

我使用了Jay的例子,並將其更改爲將所有行存儲在單個數組中以便於導出。 在結束時,你可以輕鬆地使用LogArray [0,0],以獲得從小區0的串,列0

 // create array big enough for all the rows and columns in the grid 
     string[,] LogArray = new string[dataGridView1.Rows.Count, dataGridView1.Columns.Count]; 

     int i = 0; 
     int x = 0; 
     foreach (DataGridViewRow row in dataGridView1.Rows) 
     { 
      while (x < dataGridView1.Columns.Count) 
      { 
       LogArray[i, x] = row.Cells[x].Value != null ? row.Cells[x].Value.ToString() : string.Empty; 
       x++; 
      } 

      x = 0; 
      i++; //next row 
     } 

我希望我幫助別人與此,它的我第一次張貼任何代碼在線,永遠。此外,我還沒有編碼年齡剛剛開始。