开发者

Can I assign the values to datagridview cells at a time?

开发者 https://www.devze.com 2022-12-21 22:53 出处:网络
Can I assign the values to 开发者_开发技巧datagridview cells at a time like datagridview1[0,0].value = \"zero column zero row\"

Can I assign the values to 开发者_开发技巧datagridview cells at a time like

datagridview1[0,0].value = "zero column zero row"

datagridview1[1,0].value = "first column zero row"

datagridview1[0,1].value = "zero column first row"

datagridview1[1,1].value = "first column first row"

It gives error Index was out of range. Must be non-negative and less than the size of the collection.


Try this:

    // Define 
    dataGridView1.ColumnCount = 2;
    dataGridView1.Rows.Add();

    // Assign
    dataGridView1[0, 0].Value = "zero column zero row";
    dataGridView1[1, 0].Value = "first column zero row";
    dataGridView1[0, 1].Value = "zero column first row";
    dataGridView1[1, 1].Value = "first column first row";

There is some "magic" that takes places behind the scenes. According to the MSDN document for the Cells property:

If the row does not contain any cells when this property is accessed, a new empty DataGridViewCellCollection will be created by a call to the CreateCellsInstance method.

By specifying the ColumnCount and calling the Rows.Add method the the DataGridView has enough meta information to automatically create new Rows when directly accessing the Cells property.

0

精彩评论

暂无评论...
验证码 换一张
取 消