【问题标题】:Is it possible to add a background image to the top left header of dataGridView?是否可以将背景图像添加到 dataGridView 的左上角标题?
【发布时间】:2015-09-10 08:16:13
【问题描述】:

我在 WinForms 中使用DataGridView。是否可以在DataGridView 的左上角标题中添加背景图像?左上标题,我的意思是点击后默认选择整个表格的标题。

我注意到dataGridView.TopLeftHeaderCell.Style 存在,它具有背景颜色的属性,但没有背景图像的属性。

我还尝试使用以下图形属性对其进行更改:

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.RowIndex==0 && e.ColumnIndex==0)
        {
            e.Graphics.DrawImage(myImage, e.CellBounds);
            e.Handled = true;
        }
    }

很遗憾,rowIndex == 0 && columnIndex == 0 不代表左上角的标题单元格,而是左上角的常规单元格。

【问题讨论】:

  • .NET 非常灵活,几乎可以做任何事情。问题通常不在于是否可以做某事,而在于付出什么代价以及是否真的值得。您可以根据需要修改任何(默认)控件的外观和功能。另一方面,SO 中的大多数人并不喜欢提供完全满足提问者期望的代码。你能告诉我们你到目前为止所做的尝试吗?
  • @varocarbas 抱歉,请查看编辑
  • 无需道歉。这是为了让您更快地获得帮助。此外,在这种情况下,您实际上已经解决了问题。分享你所拥有的总是一个好主意。
  • 只需将if (e.RowIndex == 0 && e.ColumnIndex == 0) 更改为if (e.RowIndex == -1 && e.ColumnIndex == -1)

标签: c# winforms datagridview


【解决方案1】:

您可以使用DataGridViewPaint 事件来绘制DataGridView

private void dataGridView1_Paint(object sender, PaintEventArgs e)
{
    e.Graphics.DrawIcon(System.Drawing.SystemIcons.Exclamation, 
                        new Rectangle(0, 0, 16, 16));
}

这是一个使用图标的示例。你也可以使用e.Graphics.DrawImage

但您需要调整图像大小以覆盖您希望背景图像覆盖的区域。

【讨论】:

    【解决方案2】:

    我遇到的问题是指左上角的标题单元格,因为第 0 行第 0 列指的是左上角的常规单元格而不是标题单元格。

    可以通过引用小于0的行和列索引来完成。参见下面的代码。

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
        {
            if (e.RowIndex<0 && e.ColumnIndex<0)
            {
                e.Graphics.DrawImage(myImage, e.CellBounds);
                e.Handled = true;
            }
        }
    

    【讨论】:

      【解决方案3】:

      嗯,这似乎有点过时,但我想提一下您帖子的编辑。

      很遗憾,rowIndex == 0 && columnIndex == 0 不代表 左上角的标题单元格,而不是左上角的常规单元格。

      请尝试以下方法:

      dataGridView1.TopLeftHeaderCell.Value = "123";

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-01-23
        • 1970-01-01
        • 1970-01-01
        • 2015-04-02
        • 2016-08-25
        • 2021-11-07
        • 1970-01-01
        相关资源
        最近更新 更多