How do I make the DataGridView show the selected r

2020-02-02 06:16发布

I need to force the DataGridView to show the selected row.

In short, I have a textbox that changes the DGV selection based on what is typed into the textbox. When this happens, the selection changes to the matching row.

Unfortunately if the selected row is out of the view, I have to manually scroll down to find the selection. Does anyone know how to force the DGV to show the selected row?

Thanks!

9条回答
别忘想泡老子
2楼-- · 2020-02-02 06:54

// This works, it's case sensitive and finds the first occurrence of search

    private bool FindInGrid(string search)
    {
        bool results = false;

        foreach (DataGridViewRow row in dgvData.Rows)
        {
            if (row.DataBoundItem != null)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    if (cell.Value.ToString().Contains(search))
                    {
                        dgvData.CurrentCell = cell;
                        dgvData.FirstDisplayedScrollingRowIndex = cell.RowIndex;
                        results = true;
                        break;
                    }

                    if (results == true)
                        break;
                }
                if (results == true)
                    break;
            }
        }

        return results;
    }
查看更多
We Are One
3楼-- · 2020-02-02 06:57

Please note that setting FirstDisplayedScrollingRowIndex when your DataGridView is not enabled will scroll the list to desired row, but scrollbar will not reflect its position. Simpliest solution is re-enabling and disabling your DGV.

dataGridView1.Enabled = true;
dataGridView1.FirstDisplayedScrollingRowIndex = index;
dataGridView1.Enabled = false;
查看更多
欢心
4楼-- · 2020-02-02 06:58

This one scrolls to the selected row without put it on top.

dataGridView1.CurrentCell = dataGridView1.Rows[index].Cells[0];
查看更多
登录 后发表回答