[英]C# datagridview column into an array
我正在用c#構建一個程序,並在其中包含了一個datagridview組件。 datagridview具有固定數量的列(2),我想將其保存到兩個單獨的數組中。 但行數確實發生了變化。 我怎么能這樣做?
假設一個名為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++;
}
我使用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
}
我希望我幫助過這個人,這是我第一次在網上發布任何代碼。 此外,我還沒有編碼,只是重新開始。
試試這個:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.