Reputation: 883
I have a datagridview (dgv) and set some shortcut for it. I want to get my desired cell value when dgv selectedIndexChanged
.
this is what I've done for selectedIndexChanged
event:
if (dgv.Rows.Count > 0)
{
lblId.Text = dgv.CurrentRow.Cells[0].Value.ToString();
lblStaffName.Text = dgv.CurrentRow.Cells[1].Value.ToString();
lblStock.Text = dgv.CurrentRow.Cells[4].Value.ToString();
}
and defined some shortcut for my dgv.
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Alt | Keys.Down))
{
if (dgv.Rows.Count > 0)
{
dgv.Focus();
if (dgv.CurrentRow.Index < (dgv.Rows.Count - 1))
{
dgv.Rows[dgv.CurrentRow.Index + 1].Selected = true;
dgv.FirstDisplayedScrollingRowIndex = dgv.CurrentRow.Index + 1;
pnl.BackColor = Color.FromKnownColor(KnownColor.Lime);
}
}
}
}
NOTE: as you can see, when I press Alt+keyDown
dgv index will increase and change to one step more.
My problem is when I pressed Alt+keyDown
the index change and selected as well but the value won't get new value until I press again Alt+keyDown
twice!
Is there any event that I must writing code in there? thanks :)
Upvotes: 1
Views: 519
Reputation: 125342
To change the selected index in a data-bound DataGridView
it's better to rely on the binding context this way:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Alt | Keys.Down))
{
var bc = dgv.BindingContext[dgv.DataSource, dgv.DataMember];
if (bc.Position < bc.Count - 1)
bc.Position++;
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
But if the DataGridView
is not data-bound or just for learning purpose you want to fix your code, you can write such code:
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Alt | Keys.Down))
{
if (dgv.CurrentCell == null)
{
if (dgv.ColumnCount >= 1 && dgv.RowCount >= 1)
{
dgv.CurrentCell = dgv[0, 0];
return true;
}
}
else
{
var rowIndex = dgv.CurrentCell.RowIndex;
var columnIndex = dgv.CurrentCell.ColumnIndex;
if (rowIndex < dgv.RowCount - 1)
{
dgv.CurrentCell = dgv[columnIndex, rowIndex + 1];
return true;
}
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
I also removed dgv.Focus()
because when you use shortcuts to navigate between rows, you don't need focus, but if you need it for any reason, use it.
Upvotes: 1