c# dataGridView单元格显示文字和图片

效果图:

1:创建列

dataGridView.Columns.Add("autoSetting", "自動設定");

2:创建行

dataGridView.Rows.Add(1);

dataGridView.Rows[0].Cells[0].Value = Image.FromFile("question-fill.png"); // 设置图片路径
dataGridView.Rows[0].Cells[0].ValueType = typeof(Image); // 设置单元格的值类型为Image
dataGridView.Rows[0].Cells[0].ToolTipText = "手動設定";

3:dataGridView绑定CellPainting事件,重新画单元格和图片及字体

private void DataGridView_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    DataGridView dataGridView = sender as DataGridView;
    if (e.ColumnIndex == 0 && e.Value is Image)
    {
        // 获取图片和文字
        Image image = (Image)e.Value;
        Font defaultFont = dataGridView1.Font;
        string text = "手動設定";
        Size imageSize = image.Size;
        Rectangle textRect = new Rectangle(e.CellBounds.Left, e.CellBounds.Top, e.CellBounds.Width, e.CellBounds.Height);

        // 设置文字格式(如颜色,字体等)
        using (Brush textBrush = new SolidBrush(e.CellStyle.ForeColor))
        {
            // 填充背景色以防止选择
            e.Graphics.FillRectangle(new SolidBrush(e.CellStyle.BackColor), textRect);
            // 绘制文字
            e.Graphics.DrawString(text, defaultFont, textBrush, textRect, StringFormat.GenericDefault);
        }

        // 绘制图片
        float textWidth = MeasureTextWidth(text, dataGridView.Font);
        e.Graphics.DrawImage(image, e.CellBounds.Left + textWidth, e.CellBounds.Top + 2);
        // 绘制单元格边框
        using (Pen pen = new Pen(dataGridView.GridColor))
        {
            // 计算下方线的位置
            int bottomLineY = e.CellBounds.Top + e.CellBounds.Height - 1;

            // 绘制下方线
            e.Graphics.DrawLine(pen, e.CellBounds.Left, bottomLineY, e.CellBounds.Right, bottomLineY);

            // 计算右方线的位置
            int rightLineX = e.CellBounds.Left + e.CellBounds.Width - 1;

            // 绘制右方线
            e.Graphics.DrawLine(pen, rightLineX, e.CellBounds.Top, rightLineX, bottomLineY);
        }

        // 防止进一步的绘制
        e.Handled = true;
    }
}

4:项目引入图片修改属性

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值