How would I go about displaying a 2-dimensional integer array into a DataGridView Control in C# .Net 4.0?
Asked
Active
Viewed 1.7k times
2 Answers
19
Follow the code sample on this page to populate the Rows
property:
http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx
Edit
Turns out this is a bit thornier than I thought. Here's a code example:
var data = new int[4,3]
{
{ 1, 2, 3, },
{ 4, 5, 6, },
{ 7, 8, 9, },
{ 10, 11, 12 },
};
var rowCount = data.GetLength(0);
var rowLength = data.GetLength(1);
for (int rowIndex = 0; rowIndex < rowCount; ++rowIndex)
{
var row = new DataGridViewRow();
for(int columnIndex = 0; columnIndex < rowLength; ++columnIndex)
{
row.Cells.Add(new DataGridViewTextBoxCell()
{
Value = data[rowIndex, columnIndex]
});
}
dataGridView1.Rows.Add(row);
}

Merlyn Morgan-Graham
- 58,163
- 16
- 128
- 183
12
to get Merlyn's solution to work you'll need to set the column count before you add rows to the datagridview:
dataGridView1.ColumnCount = 3;

randoms
- 2,793
- 1
- 31
- 48
-
2It should be a comment not a solution – boctulus Mar 01 '16 at 00:14
-
1It should. I was new to stackoverflow at the time when I wrote the answer (comment). – randoms Mar 01 '16 at 06:40