代码之家  ›  专栏  ›  技术社区  ›  Angle.Bracket

如何使用图标呈现数据绑定的WinForms DataGridView列?

  •  2
  • Angle.Bracket  · 技术社区  · 6 年前

    在我的C#Windows窗体应用程序中,我有一个 DataGridView 这是必然的 BindingList<Item> 依次用字母缩写的列表 List<Item>

    // bind view to controller
    myDataGridView.DataBindings.Add("DataSource", myController, "Items");
    
    // bind controller to model
    Items = new BindingList<Item>(model.Items);
    

    Item . 我为 数据表格控件 s CellFormatting 项目 类型:

    myDataGridView.CellFormatting += new DataGridViewCellFormattingEventHandler(myontroller.HandleCellFormatting);
    

    项目

    1 回复  |  直到 6 年前
        1
  •  4
  •   Reza Aghaei    6 年前

    你需要处理 CellPainting 事件 DataGridView

    此示例显示如何在绑定列中绘制图像 数据表格控件

    enter image description here

    Image zero, negative, positive;
    

    Load 事件和来自文件、资源或存储图像并分配给这些变量的任何位置的图像。设置数据绑定。为要在其中绘制图标的单元格设置适当的左填充:

    private void Form1_Load(object sender, EventArgs e)
    {
        var list = new[] {
            new { C1 = "A", C2 = -2 },
            new { C1 = "B", C2 = -1 },
            new { C1 = "C", C2 = 0 },
            new { C1 = "D", C2 = 1 },
            new { C1 = "E", C2 = 2 },
        }.ToList();
        dataGridView1.DataSource = list;
    
        zero = new Bitmap(16, 16);
        using (var g = Graphics.FromImage(zero))
            g.Clear(Color.Silver);
        negative = new Bitmap(16, 16);
        using (var g = Graphics.FromImage(negative))
            g.Clear(Color.Red);
        positive = new Bitmap(16, 16);
        using (var g = Graphics.FromImage(positive))
            g.Clear(Color.Green);
    
        //Set padding to have enough room to draw image
        dataGridView1.Columns[1].DefaultCellStyle.Padding = new Padding(18, 0, 0, 0);
    }
    

    细胞绘画 数据表格控件

    private void DataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        //We don't need custom paint for row header or column header
        if (e.RowIndex < 0 || e.ColumnIndex != 1) return;
    
        //We don't need custom paint for null value
        if (e.Value == null || e.Value == DBNull.Value) return;
    
        //Choose image based on value
        Image img = zero;
        if ((int)e.Value < 0) img = negative;
        else if ((int)e.Value > 0) img = positive;
    
        //Paint cell
        e.Paint(e.ClipBounds, DataGridViewPaintParts.All);
        e.Graphics.DrawImage(img, e.CellBounds.Left + 1, e.CellBounds.Top + 1,
            16, e.CellBounds.Height - 3);
    
        //Prevent default paint
        e.Handled = true;
    }
    

    手柄 FormClosing 事件来处理图像:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
    {
        //Dispose images
        if (zero != null) zero.Dispose();
        if (negative != null) negative.Dispose();
        if (positive != null) positive.Dispose();
    }