Reputation: 44393
I'd like to use the DataGridView control as a list with columns. Sort of like ListView in Details mode but I want to keep the DataGridView flexibility.
ListView (with Details view and FullRowSelect enabled) highlights the whole line and shows the focus mark around the whole line:
DataGridView (with SelectionMode = FullRowSelect) displays focus mark only around a single cell:
So, does anyone know of some (ideally) easy way to make the DataGridView row selection look like the ListView one?
I'm not looking for a changed behaviour of the control - I only want it to look the same.
Ideally, without messing up with the methods that do the actual painting.
Upvotes: 34
Views: 58707
Reputation: 451
If you want the focus rectangle to be around the entire row rather than the single cell, you can use the below code. It assumes that your DataGridView is named gvMain and that it has SelectionMode set to FullRowSelect and MultiSelect set to False.
private void gvMain_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
// Draw our own focus rectangle around the entire row
if (gvMain.Rows[e.RowIndex].Selected && gvMain.Focused)
ControlPaint.DrawFocusRectangle(e.Graphics, e.RowBounds, Color.Empty, gvMain.DefaultCellStyle.SelectionBackColor);
}
private void gvMain_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
// Disable the original focus rectangle around the cell
e.PaintParts &= ~DataGridViewPaintParts.Focus;
}
private void gvMain_LeaveAndEnter(object sender, EventArgs e)
{
// Redraw our focus rectangle every time our DataGridView receives and looses focus (same event handler for both events)
gvMain.InvalidateRow(gvMain.CurrentRow.Index);
}
Upvotes: 0
Reputation: 645
How about
SelectionMode == FullRowSelect
and
ReadOnly == true
It works for me.
Upvotes: 22
Reputation: 44393
Put this code either into your form's constructor or set it in datagridview's Properties using the IDE.
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.MultiSelect = false;
dgv.RowPrePaint +=new DataGridViewRowPrePaintEventHandler(dgv_RowPrePaint);
Then paste the following event into the form code:
private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
e.PaintParts &= ~DataGridViewPaintParts.Focus;
}
And it works! :-)
"dgv" is the DataGridView in question and "form" is the Form that contains it.
Note, that this soulution doesn't display the dotted rectangle around the whole row. Instead, it removes the focus dots entirely.
Upvotes: 48