Sealer_05
Sealer_05

Reputation: 5566

C# How to reposition row selection on DataGridView programmatically

I am using linq2sql to add a record to my datagridview and refreshing the grid. Right now after refresh it moves the row selection to the top. How would I tell it to highlight the most recent added record?

Not sure if this would help but I have included the code below I am using to find out the pk of the selected row. As what I would like to do is kind of the opposite. Thanks

        //get selected row index
        int index = this.dataGridView1.CurrentRow.Index;
        //get pk of selected row using index
        string cellValue = dataGridView1["pkColumn", index].Value.ToString();
        //change pk string to int
        int pKey = Int32.Parse(cellValue);

Upvotes: 1

Views: 5172

Answers (1)

Luis Quijada
Luis Quijada

Reputation: 2405

If you know in advance that anytime a new item is added, it should appear at the bottom of the list, you could use:

    int index = this.dataGridView1.Rows.Count - 1;
    this.dataGridView1.Rows[index].Selected = true;
    this.dataGridView1.FirstDisplayedScrollingRowIndex = index;

But, if your order the list by other column then you're not going to get the desired results.

I recommend you, is to search for the row-index you need to give the selection to, this could be performed by a function, let's say int SearchRowIndexForPKValue(int pKey), that will perform a look-up within the cell values of the column that contains your PK/ID ("pkColumn") returning the row index. In such way the code above should looks like:

    int index =  SearchRowIndexForPKValue(pKey);
    this.dataGridView1.Rows[index].Selected = true;
    this.dataGridView1.FirstDisplayedScrollingRowIndex = index;

EDIT: int SearchRowIndexForPKValue(int pKey) is not an existing built-in method of the DataGridView. You must declare it and implement it in your code; for the body of the method, you can get the code from this post.

Upvotes: 4

Related Questions