My winforms skills are a bit rusty. I'm using a BindingSource
for a DataGridView
. On KeyDown
of the DataGridView
i want to select the next/previous record which works as desired.
I want to select the first if the user hits Keys.Down
when the last item is selected and select the last if he hits Keys.Up
when the first item is selected. But nothing happens then.
Here's the code:
private void Grid_Keydown(Object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Up)
previousItem();
else if (e.KeyCode == Keys.Down)
nextItem();
}
private void previousItem()
{
BindingSource bs = null;
switch (this.Type) // a custom enum
{
case AdminType.Channel:
bs = channelBindingSource;
break;
default:
break;
}
if (bs.Position - 1 < 0)
bs.MoveLast();
else
bs.MovePrevious();
}
private void nextItem()
{
BindingSource bs = null;
switch (this.Type)
{
case AdminType.Channel:
bs = channelBindingSource;
break;
default:
break;
}
if (bs.Position + 1 >= bs.Count)
bs.MoveFirst();
else
bs.MoveNext();
}
Note that bs.MoveFirst()
/bs.MoveLast()
are called correctly but nothing happens.
Edit: Interesting, it works as expected when i trigger this from a button(previous/next) instead of the DataGridView
's OnKeyDown
, any ideas?
KeyUp
– UnpracticalKeys.Up/Down
. What can cause it? – FairfieldKeys.Up
is to focus the previos row - therby automaticly updating thebs.Position
. – UnpracticalMoveFirst
andMoveLast
. But the next problem is that i cannot detect when the last item is selected sinceBindingSource.Position
is set before the KeyUp event is triggered. You may want to answer it anyway so i can upvote/accept it. – Fairfieldbs.PositionChanged
event instead of the grid. – UnpracticalKeys.Up
is pressed, the last item should be selected and if the last item was selected and the user hitsKeys.Down
then first should be selected. How wouldPositionChanged
help to identify if the user wants the next or previous item? It would be triggered only if the position was already changed and not on the first or last position(which is the only relevant event). – FairfieldPositionChanged
, so you might want to post an answer with your comments. I can add my code afterwards. Maybe there's something easier but it works. – Fairfield