Harikrishna
Harikrishna

Reputation: 4305

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

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.

Upvotes: 1

Views: 4719

Answers (1)

Philip Fourie
Philip Fourie

Reputation: 116957

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.

Upvotes: 1

Related Questions