【问题标题】:Set a DataGridView Cell Border Style to selected column only仅将 DataGridView 单元格边框样式设置为选定列
【发布时间】:2018-12-16 13:25:20
【问题描述】:

我想在我的第 3 列的单元格上使用这种边框样式。
谁能帮我在 DataGridView 中完成这项工作。

我说的是带有红色矩形的选定部分:

【问题讨论】:

  • 也许this 可以帮忙..

标签: c# .net winforms datagridview


【解决方案1】:

我们在问题的指定列中可以看到的边框不是单元格边框。单元格边框是行之间的那些点线。所以在CellPaint 方法中设置AdvancedBorderStyle 不会有太大帮助。

您需要执行一些设置并进行一些自定义绘画。

这些设置可以帮助您为行和单元格实现这种样式:

  • 为列设置填充
  • 设置行高
  • 将单元格边框样式设置为无
  • 删除行标题
  • 处理CellPaint事件:
    • 绘制单元格但内容。
    • 在行的顶部和底部绘制虚线边框。
    • 正常绘制单元格内容或像特定列的文本框一样绘制。

示例

var specificColumn = 1;

dataGridView1.Columns[specificColumn].DefaultCellStyle.Padding = new Padding(10);
dataGridView1.RowTemplate.Height = 45;
dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;
dataGridView1.RowHeadersVisible = false;

dataGridView1.CellPainting += (obj, args) =>
{
    if (args.ColumnIndex < 0 || args.RowIndex < 0)
        return;
    args.Paint(args.CellBounds, DataGridViewPaintParts.All & 
        ~DataGridViewPaintParts.ContentForeground);
    var r = args.CellBounds;
    using (var pen = new Pen(Color.Black))
    {
        pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
        args.Graphics.DrawLine(pen, r.Left, r.Top, r.Right, r.Top);
        args.Graphics.DrawLine(pen, r.Left, r.Bottom, r.Right, r.Bottom);
    }
    r.Inflate(-8, -8);
    if (args.ColumnIndex == specificColumn)
        TextBoxRenderer.DrawTextBox(args.Graphics, r, $"{args.FormattedValue}",
            args.CellStyle.Font, System.Windows.Forms.VisualStyles.TextBoxState.Normal);
    else
        args.Paint(args.CellBounds, DataGridViewPaintParts.ContentForeground);
    args.Handled = true;
};

【讨论】:

  • 对。我可能误读了这个问题,重点是 我说的是带有红色矩形的选定部分(和绘图)。我将其解释为应用于特定列边界的边框。
  • @Jimi 标题是关于将边框样式应用于特定列。在这种情况下,AdvancedBorderStyle 非常有用。但是图像在说不同的事情(我在答案中解释过)。
  • 我认为你做对了。图片中显示的 Cells 风格可能不是 OP 已经拥有的,而是他想要实现的。
猜你喜欢
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多