Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Caret in column won't move after selecting currentcell in datagridview

I read the way you move the row indicator(the little black caret) is by setting the datagridview.currentcell property. When I do this it sets the current cell appropriately, but it still won't move the row indicator. I do this after adding a row to my datagridview.

    Private Sub dataGridView_RowsAdded(sender As Object, e As DataGridViewRowsAddedEventArgs) Handles dataGridView.RowsAdded
        if(not dataGridView.rows(e.rowindex).isnewrow)
        dataGridView.currentCell = dataGridView.Item(dataGridView.firstDisplayedCell.columnindex, e.rowindex)
        end if
    end sub
like image 883
Luminous Avatar asked Nov 22 '25 00:11

Luminous


1 Answers

I got something to work, but it seems like an odd way to do it. It is written in c# but should be applicable to VB. I set up a private class level variable called r that stores the new row index. Before the row is painted, I reset the currentcell to the desired cell and call DGV.Refresh(). This seems to do what you want, but not very pretty.

 {
     dataGridView1.RowsAdded += dataGridView1_RowsAdded;
     dataGridView1.RowPrePaint += dataGridView1_RowPrePaint;
 }

 bool temp = false;
 int r;

 void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
 {            
     if (!dataGridView1.Rows[e.RowIndex].IsNewRow)
     {
         r = e.RowIndex;
         dataGridView1.CurrentCell = dataGridView1[dataGridView1.FirstDisplayedCell.ColumnIndex, r];
         temp = true;
     }
 }

 void dataGridView1_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
 {
     if (temp)
     {
         temp = false;
         dataGridView1.CurrentCell = dataGridView1[dataGridView1.FirstDisplayedCell.ColumnIndex, r];
         dataGridView1.Refresh();
     }
 }
like image 87
Moop Avatar answered Nov 24 '25 19:11

Moop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!