JPProgrammer February 2016

How to force DataGridView current cell outline without pressing Tab

Is there someway to make it so the current cell of the DataGridView always has the dashed-line border around it that you get when you press the Tab button? I've noticed that if you've pressed the Tab button once after that the current cell always has the border around it, but I'd like to have that border there from the start, without having to press the Tab button.

Currently I'm programmatically sending the Tab key, as below:

SendKeys.Send("{TAB}");

But this is kludgy and I'd rather have a proper solution if one is available.

Edit: I forgot to mention that the SelectionMode is set to FullRowSelect and I'm not looking to change this. I want the border outline around just the current cell as well as the whole row being highlighted.

Answers


Bioukh February 2016

This behavior seems to be hardcoded in windows forms. I don't think you could find a better way to code it.

One suggestion I can propose you is to handle the DataGridView.CellPainting event and to draw manually the border. You will then be able to draw the border with the style you want, so that the current cell could be more visible for the user than with the "TAB" method. Here is an example with a red dashed border :

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (dataGridView1.CurrentCell != null && e.RowIndex != -1 && e.ColumnIndex != -1 &&
        dataGridView1.CurrentCell.RowIndex == e.RowIndex &&
        dataGridView1.CurrentCell.ColumnIndex == e.ColumnIndex)
    {
        e.Paint(e.ClipBounds, e.PaintParts);
        var pen = new Pen(Color.Red) { DashStyle = DashStyle.Dash };
        var rect = new Rectangle(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width - 2, e.CellBounds.Height - 2);
        e.Graphics.DrawRectangle(pen, rect);
        e.Handled = true;
    }
}


OhBeWise February 2016

Create a new class to inherit from DataGridView and override the ShowFocusCues property - returning True to always show the focus rectangle or False to never show it. You could even add a public property to expose it if you want to change it on a whim.

public class DataGridViewFocused : DataGridView
{
    public bool ShowFocus { get; set; }

    protected override bool ShowFocusCues
    {
        get
        {
            return this.ShowFocus;
        }
    }
}

DataGridViewFocused dataGridView1 = new DataGridViewFocused();
dataGridView1.ShowFocus = true;

Note: This will only focus the CurrentCell as that is just how it behaves. So even with FullRowSelect set, only one of the selected cells in the highlighted row will be focused.

Post Status

Asked in February 2016
Viewed 3,351 times
Voted 9
Answered 2 times

Search




Leave an answer