如何在二维数组中获取DataGridView数据?

时间:2014-09-09 14:03:22

标签: c# arrays datagridview

在我的应用程序中,我试图将datagridview(5rows和5columns)数据转换为2d数组,任何人都可以 帮助将数据输入到数组......

        int countColumn = dataGridView1.ColumnCount -1;
        int j=0,k=0;
        string dataFromGrid = "";
        foreach (DataGridViewRow i in dataGridView1.Rows)
        {
            if (!i.IsNewRow)
            {


                //dataFromGrid = r.Cells[0].Value.ToString();

                for ( j = 0; j <= countColumn; j++)
                {
                    dataFromGrid = dataFromGrid + i.Cells[j].Value.ToString();


                }

            }
           var[k,j], Convert.ToInt32(dataFromGrid)
           k=k+1;

3 个答案:

答案 0 :(得分:3)

如果你喜欢foreach循环,你可以这样做:

var array = new object[dataGridView1.RowCount,dataGridView1.ColumnCount];
foreach (DataGridViewRow i in dataGridView1.Rows)
{
    if (i.IsNewRow) continue;
    foreach (DataGridViewCell j in i.Cells)
    {
        array[j.RowIndex, j.ColumnIndex] = j.Value;
    }
}

答案 1 :(得分:1)

object[,] arr2d = new object[dataGridView1.Rows.Count,dataGridView1.Columns.Count];

for (int x = 0; x < arr2d.GetLength(0); x++)
     for (int i = 0; i < arr2d.GetLength(1); i++)
            arr2d[x, i] = dataGridView1.Rows[x].Cells[i].Value;

这应该有效

答案 2 :(得分:0)

//first of all create a 2D array varialble and count the rows and //column of data grid view
string[,] dataValue = new string[gridViewBillingItems.Rows.Count, gridViewBillingItems.Columns.Count];

//loop through the rows of data grid view 
foreach (DataGridViewRow row in gridViewBillingItems.Rows)
{
    //getting index of row
    int i = row.Index;
    //loop through the column of data grid view

    foreach (DataGridViewColumn col in gridViewBillingItems.Columns)
    {
        //getting index of column
        int j = col.Index;
        //add all the rows and column to 2D Array
        dataValue[row.Index, col.Index] = gridViewBillingItems.Rows[i].Cells[j].Value.ToString();
    }
}