简体   繁体   中英

C# DataGridView set focus on a row instead of cell when hit TAB

I have a winforms datagridview, when I hit TAB, the focus rectangle (dotted rectangle) sets to a cell and starts moving from cell to cell as I keep hitting the button, instead I want the rectangle to be set to the entire row not just the cell and once I start hitting TAB it should move from row to row .

I have tried setting the selctionmode to fullrowselect but still the focus sets for cell. 在此处输入图片说明 在此处输入图片说明

Can you please suggest me any workaround to achieve the objective here. Thanks!

You can use with SelectionMode as FullRowSelect the datagridview s KeyDown event such as

private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Tab)
    {
        int activeRow = dataGridView1.CurrentCell.RowIndex;
        if ((activeRow + 1) < dataGridView1.RowCount)
        {
            dataGridView1.CurrentCell = dataGridView1.Rows[activeRow+1].Cells[0];
        }
    }
}

Also for selection rectangle you can add in the CellPainting event the folowing code

void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex == this.dataGridView1.CurrentCell.ColumnIndex
            && e.RowIndex == this.dataGridView1.CurrentCell.RowIndex)
        {
            e.Paint(e.CellBounds, DataGridViewPaintParts.All& ~DataGridViewPaintParts.Border);
            using (Pen p = new Pen(Color.Black, 0))
            {
                Rectangle rect = e.CellBounds;
                rect.Width -= 2;
                rect.Height -= 2;
                e.Graphics.DrawRectangle(p, rect);
            }
            e.Handled = true;
        }
    }

Try This.,

Using Tab:

dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

Using Mouseclick:

dataGridView1.SelectionMode = DataGridViewSelectionMode.RowHeaderSelect;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM