.net DataGridView:如何聚焦整行而不是单个单元格?
我想使用DataGridView控件作为列的列表。有点像细节模式下的ListView,但我想保持DataGridView的灵活性 ListView(启用了详细信息视图和FullRowSelect)高亮显示整行并显示整行周围的焦点标记:.net DataGridView:如何聚焦整行而不是单个单元格?,.net,winforms,datagridview,.net,Winforms,Datagridview,我想使用DataGridView控件作为列的列表。有点像细节模式下的ListView,但我想保持DataGridView的灵活性 ListView(启用了详细信息视图和FullRowSelect)高亮显示整行并显示整行周围的焦点标记: DataGridView(使用SelectionMode=FullRowSelect)仅在单个单元格周围显示焦点标记: 那么,有人知道一些(理想情况下)使DataGridView行选择看起来像ListView行选择的简单方法吗? 我不想改变控件的行为-我只想让
DataGridView(使用SelectionMode=FullRowSelect)仅在单个单元格周围显示焦点标记:
那么,有人知道一些(理想情况下)使DataGridView行选择看起来像ListView行选择的简单方法吗?
我不想改变控件的行为-我只想让它看起来一样。
理想情况下,不要弄乱实际绘制的方法。将此代码放入表单的构造函数中,或者使用IDE在datagridview的属性中设置它
dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dgv.MultiSelect = false;
dgv.RowPrePaint +=new DataGridViewRowPrePaintEventHandler(dgv_RowPrePaint);
然后将以下事件粘贴到表单代码中:
private void dgv_RowPrePaint(object sender, DataGridViewRowPrePaintEventArgs e)
{
e.PaintParts &= ~DataGridViewPaintParts.Focus;
}
而且它是有效的!:-)
“dgv”是有问题的DataGridView,“form”是包含它的表单
请注意,此解决方案不会显示整行周围的虚线矩形。相反,它会完全去除焦点。怎么样
SelectionMode == FullRowSelect
及
它适合我。如果希望焦点矩形围绕整行而不是单个单元格,可以使用以下代码。 它假定您的DataGridView名为gvMain,并且SelectionMode设置为FullRowSelect,MultiSelect设置为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);
}
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);
}