二维Integer数组到DataGridView

时间:2010-11-06 00:58:34

标签: c# .net datagridview .net-3.5 .net-4.0

如何在C#.Net 4.0中的DataGridView控件中显示二维整数数组?

2 个答案:

答案 0 :(得分:18)

按照此页面上的代码示例填充Rows属性:

http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx

修改

事实证明这比我想象的要有点棘手。这是一个代码示例:

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);
}

答案 1 :(得分:11)

要使Merlyn的解决方案正常工作,您需要在向datagridview添加行之前设置列数:

dataGridView1.ColumnCount = 3;