ComanderKai77 ComanderKai77 - 1 month ago 8
C# Question

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)
{

}


?

Answer

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.

Comments