Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically change selection on DatagridView (.NET)

I'm learning VB.NET.

I've a problem with DataGridView component when trying to set the value of the CurrentCell. What i'm trying to do is :

I've a DataGridView With values. I want to make a button in my forms and when clicking on it I want to change the selection from the current row to the next. To explain more, by clicking my Button I want to simulate the effect of a mouse click on a DataGridview.

I hope you can help me,

Thanks!

like image 418
Dali Avatar asked Feb 22 '09 14:02

Dali


3 Answers

Maybe something like this:

    If DataGridView1.RowCount > 0 Then

        Dim MyDesiredIndex As Integer = 0

        If DataGridView1.CurrentRow.Index < DataGridView1.RowCount - 1 Then
            MyDesiredIndex = DataGridView1.CurrentRow.Index + 1
        End If

        DataGridView1.ClearSelection()            
        DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)
        DataGridView1.Rows(MyDesiredIndex).Selected = True

    End If

Note 1: maybe these two lines are not necessary. I haven´t proved it

        DataGridView1.ClearSelection()            
        DataGridView1.CurrentCell = DataGridView1.Rows(MyDesiredIndex).Cells(0)

Note 2: note that if we are in the last row, it goes to first

like image 167
Javier Avatar answered Nov 19 '22 08:11

Javier


If your data grid is bound to a BindingSource, it is better to change the position there:

Object key = Convert.ToInt32(cdr["WordList"]);
int itemFound = lexiconNamesBindingSource.Find("ID_Name", key);
lexiconNamesBindingSource.Position = itemFound;

...and you might need to finish it off with:

lexiconNamesBindingSource.ResetBidings();

(This is an old thread, but I found it, so someone else might find this useful)

like image 2
Alex Russell Avatar answered Nov 19 '22 07:11

Alex Russell


You need to set the particular row's Selected property to true. I think the VB would be something like this:

someDGV.Rows(index).Selected = True
like image 5
Beep beep Avatar answered Nov 19 '22 08:11

Beep beep