我正在用c#構建一個程序,並在其中包含了一個datagridview組件。 datagridview具有固定數量的列(2),我想將它們保存到兩個單獨的數組中。行數量確實發生了變化。我怎麼能這樣做?將C#datagridview列轉換爲數組
回答
試試這個:
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);
}
假設一個名爲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++;
}
+1,可能稍微更有效。 – 2011-04-07 18:34:26
@Abe當然,如果他使用的是.NET 2.0+,我們建議使用List
對我而言,確實如此,但我的印象是,如果您事先知道集合的長度,通常使用陣列更好/更高效(儘管性能增益可能不明顯)。 – 2011-04-07 18:47:28
我使用了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
}
我希望我幫助別人與此,它的我第一次張貼任何代碼在線,永遠。此外,我還沒有編碼年齡剛剛開始。
- 1. 將數組轉換爲數組列表?
- 2. C#Datagridview - 將TextColumn轉換爲ComboBoxColumn
- 3. 將DataGridView的內容轉換爲C#中的列表#
- 4. 將IEnumerable對象列表轉換爲對象數組列表C#
- 5. 將列表中的asp.net mvc c#列表轉換爲javascript數組
- 6. 將Lua錶轉換爲C數組?
- 7. 如何將C#數組轉換爲XML
- 8. 將C轉換爲MIPS - 嵌套數組
- 9. 將C++轉換爲更小的數組
- 10. 將C#字節數組轉換爲VB.NET
- 11. 將Datatable轉換爲C#中的數組
- 12. C++將int轉換爲字符數組?
- 13. 將C#數組轉換爲MWarray Matlab
- 14. C#如何將CSV轉換爲數組?
- 15. 將C#SurfaceListBox轉換爲JSON數組
- 16. 將Fortran多維數組轉換爲C
- 17. 將數組轉換爲隊列
- 18. 將Nsmutable陣列轉換爲Mkannotation數組
- 19. 將列表轉換爲數組。 java.lang.ArrayStoreException
- 20. 將數組轉換爲嵌套列表
- 21. 將列表轉換爲數組
- 22. 如何將數組轉換爲列表
- 23. 將列表數組轉換爲表
- 24. 如何將表列轉換爲數組?
- 25. 將數組隱式轉換爲列表
- 26. 將.csv轉換爲數組列表
- 27. 將列表轉換爲數組
- 28. 將陣列數組轉換爲矩陣
- 29. 將整數轉換爲組合框中的數字列表 - C#
- 30. 如何將目標C數組轉換爲C數組?
在使用Jay的代碼時,第一次得到錯誤之後,我試了一下 - 它確實有效。但是,如果你說傑伊的效率更高,我可能會繼續試驗! – Xedfire 2011-04-07 21:49:32