在 C# Winforms 中的 DataGridViewCell 内绘制实心圆形或矩形

2023-11-26

我想在圆的中心画一个小实心圆DataGridViewCell。矩形也能达到这个目的。我想我必须在 CellPainting 事件中执行此操作。

我已经尝试过这个:

if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
        {                
            if (dgv_Cuotas.Columns[e.ColumnIndex].Name == "Seleccionar" && Convert.ToBoolean(dgv_Cuotas.Rows[e.RowIndex].Cells["pagada"].Value) == true)
            {
                e.CellStyle.BackColor = Color.LightGray; ;
                e.PaintBackground(e.ClipBounds, true);
                e.Handled = true;
            }
        }

enter image description here

它绘制了整个单元格,我只想要一个小圆圈或矩形,如下图所示:

enter image description here

我怎样才能实现这个目标? 使用 DataGridViewImageCell 不是一个选项,因为我遇到格式错误。我只需将 DataGridViewCheckBoxCell 更改为 DataGridViewTextboxCell。

EDIT:我可以将其更改为 DataGridView Image Cell!不知道之前发生了什么,但我仍然无法加载图像。我只是得到一个带有红十字的白色方块(无图像图标)。这是我的代码:

dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"] = new DataGridViewImageCell();
dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"].Value = Properties.Resources.punto_verde;
dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"].Style.ForeColor = Color.White;
dgv_Cuotas.Rows[row.Index].Cells["Seleccionar"].Style.SelectionForeColor = Color.White;

感谢您的提问和回答@Andres。

请看我的回复: (例如)我有一个包含 2 列的 datagridview。在第一列中,我想显示一个色环,其颜色在第二列中写入(颜色名称)。为此,我的代码是:

for (int i = 1; i <= 5; i++)
    Dgv.Rows.Add();
Dgv[1, 0].Value = "Red";
Dgv[1, 1].Value = "Blue";
Dgv[1, 2].Value = "Yellow";
Dgv[1, 3].Value = "Green";
Dgv[1, 4].Value = "Black";

为了创建一个圆圈,我编写了此类代码:

public static class GraphicsExtensions
{
    public static void FillCircle(this Graphics g, Brush brush, float centerX, float centerY, float radius)
    {
        g.FillEllipse(brush, centerX - radius, centerY - radius, radius + radius, radius + radius);
    }
}

在我的 datagridview 的 CellPainting 事件中,编写以下代码:

private void Dgv_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.ColumnIndex == 0 && e.RowIndex > -1)
    {
        Brush Brs= new SolidBrush(Color.FromName(Dgv[1, e.RowIndex].Value.ToString()));
        GraphicsExtensions.FillCircle(e.Graphics, Brs, e.CellBounds.Location.X + 5, e.CellBounds.Location.Y + 10, 5);
        e.Handled = true;                
    }
}

结果是包含 2 列的 datagridview:

第 1 列:6 个圆圈,有 6 种特定颜色

第 2 列:6 种颜色名称

Thanks.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 C# Winforms 中的 DataGridViewCell 内绘制实心圆形或矩形 的相关文章

随机推荐