ComanderKai77
ComanderKai77

Reputation: 492

DataGridView set CurrentCell not working

I'm trying to populate a DataGridView and preselect a cell. But it is not working well. I'm creating the DataGridView with this code:

DataTable table = new DataTable();
table.Columns.Add("Column1");
table.Columns.Add("Column2");
table.Rows.Add("Row1");
table.Rows.Add("Row2");
table.Rows.Add("Row3");
table.Rows.Add("Row3");
table.Rows.Add("Row4");
table.Rows.Add("");

dataGridView1.DataSource = table;
dataGridView1.ReadOnly = false;
dataGridView1.Columns["Column1"].ReadOnly = true;
dataGridView1[1, 2].ReadOnly = true;
dataGridView1[1, 3].ReadOnly = true;

DataGridViewButtonCell button = new DataGridViewButtonCell();
dataGridView1[1, table.Rows.Count - 1] = button;
button.Value = "Go";
button.FlatStyle = FlatStyle.Flat;

dataGridView1.CurrentCell = dataGridView1[0, 1];

In theory the first cell on the right side should be selected but the 3rd row in the 1st column is selected. Could this problem result with this:

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{

}

Or

private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{

}

?

Upvotes: 0

Views: 6642

Answers (2)

Ivan Stoev
Ivan Stoev

Reputation: 205539

You use the following

dataGridView1.CurrentCell = dataGridView1[0, 1];

and say

In theory the first cell on the right side should be selected

In fact, the arguments for the cell indexer are columnIndex, rowIndex, so the above should select the first column of the second row, which it indeed does. Use dataGridView[1, 0] if you intend to select the second column of the first row.

Upvotes: 1

Salah Akbari
Salah Akbari

Reputation: 39946

When you want to set the dataGridView1.CurrentCell you should note that in the dataGridView1[0, 1] first number is the columnIndex and second number is the rowIndex. So if you want to select the first cell on the right side you should try this:

dataGridView1.CurrentCell = dataGridView1[1,0];//first row second column

Upvotes: 1

Related Questions