Show 2d-array in DataGridView

后端 未结 3 1635
不知归路
不知归路 2021-01-16 19:13

I have a 2D array. I want to print the array in my DataGridView but it throws an error:

[Argument OutOfRangeException was unhandled ]

相关标签:
3条回答
  • 2021-01-16 19:14

    As comments have pointed out, you should focus on rows and cells. You need to build your DataGridView columns and then populate each row cell by cell.

    The width of your array should correspond to your dgv columns and the height to the dgv rows. Take the following as a simple example:

    string[,] twoD = new string[,]
    {
      {"row 0 col 0", "row 0 col 1", "row 0 col 2"},
      {"row 1 col 0", "row 1 col 1", "row 1 col 2"},
      {"row 2 col 0", "row 2 col 1", "row 2 col 2"},
      {"row 3 col 0", "row 3 col 1", "row 3 col 2"},
    };
    
    int height = twoD.GetLength(0);
    int width = twoD.GetLength(1);
    
    this.dataGridView1.ColumnCount = width;
    
    for (int r = 0; r < height; r++)
    {
      DataGridViewRow row = new DataGridViewRow();
      row.CreateCells(this.dataGridView1);
    
      for (int c = 0; c < width; c++)
      {
        row.Cells[c].Value = twoD[r, c];
      }
    
      this.dataGridView1.Rows.Add(row);
    }
    
    0 讨论(0)
  • 2021-01-16 19:19

    The first potential problem is with how you are accessing your array indexes. Which can be handled this way.

    string[,] a = {
      {"0", "1", "2"},
          {"0", "1", "2"},
          {"0", "1", "2"},
          {"0", "1", "2"},
      };
    
    for (int i = 0; i < a.GetLength(0); i++)
    {
        for (int j = 0; j < a.GetLength(1); j++)
        {
            Console.WriteLine(a[i,j]);
        }
    }
    

    Just check your array dimension length first. Clearly one of your variables height or width is incorrect.

    This is done using Array.GetLength(int dimension)

    The second problem is how you are adding items to your datagridview.

    0 讨论(0)
  • 2021-01-16 19:28

    for exemple for 2 elements

    dataGridView1.ColumnCount = 2;
    var dataArray = new int[] { 3, 4, 4, 5, 6, 7, 8 };
    for (int i = 0; i < dataArray.Count; i++)
    {
       dataGridView1.Rows.Add(new object[] { i, dataArray[i] });
    }
    
    0 讨论(0)
提交回复
热议问题