按钮列的DataGridView图像

时间:2016-03-27 23:04:35

标签: c# .net winforms datagridview

我正在尝试将可点击的图片/按钮添加到datagridview按钮列。

图像/按钮将是播放或停止的图标。如果用户单击播放按钮,则启动系统上的服务,如果用户单击停止按钮,则服务停止。

我已经编写了启动和停止服务的函数。我遇到的困难是让按钮/图像显示在数据网格中并使其可点击。

以下是我的代码:

this.dgrdServices.RowPrePaint +=new DataGridViewRowPrePaintEventHandler(dgv_RowPrePaint);
this.dgrdServices.Rows.Add();
this.dgrdServices.Rows[0].Cells[0].Value = Image.FromFile(@"C:\users\brad\desktop\green-dot.gif"); 
this.dgrdServices.Rows[0].Cells[1].Value = "MyServer";
this.dgrdServices.Rows[0].Cells[2].Value = "MyService";
this.dgrdServices.Rows[0].Cells[3].Value = "Started";
this.dgrdServices.Rows[0].Cells[4].Value = new DataGridViewButtonCell();
this.dgrdServices.Rows[0].Cells[5].Value = "Uninstall";

如果最好使用一个图像按钮或一个可点击的图像,我就无法解决这个问题。我也无法正确显示按钮。

由于 布拉德

1 个答案:

答案 0 :(得分:17)

在按钮上显示图像

您可以添加DataGridViewButtonColumn,然后处理网格的CellPainting事件,并检查是否针对按钮列引发了事件,然后在其上绘制图像。活动结束时,请勿忘记设置e.Handled = true;

在下面的代码中我假设你有像SomeImage这样的图像资源:

private void grid_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex < 0)
        return;

    //I supposed your button column is at index 0
    if (e.ColumnIndex == 0)
    {
        e.Paint(e.CellBounds, DataGridViewPaintParts.All);

        var w = Properties.Resources.SomeImage.Width;
        var h = Properties.Resources.SomeImage.Height;
        var x = e.CellBounds.Left + (e.CellBounds.Width - w) / 2;
        var y = e.CellBounds.Top + (e.CellBounds.Height - h) / 2;

        e.Graphics.DrawImage(Properties.Resources.SomeImage, new Rectangle(x, y, w, h));
        e.Handled = true;
    }
}

不带按钮显示图片

要在包括新行的所有行上显示单个图像,您可以设置Image的{​​{1}}属性。这样,图像将显示在所有行的列中:

DataGridViewImageColumn

此外,如果您可能希望为单元格设置不同的图像,则可以在dataGridView1.Columns.Add(new DataGridViewImageColumn(){ Image = Properties.Resources.SomeImage, Name = "someName", HeaderText = "Some Text" }); 事件中设置DataGridViewImageColumn的格式化值:

CellFormatting

您还可以将void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.RowIndex < 0) return; //I supposed the image column is at index 1 if (e.ColumnIndex == 1) e.Value = Properties.Resources.SomeImage; } Image属性设置为图像,但图像不会显示在新行上。

处理点击

要处理点击图片/按钮,您可以处理DataGridViewImageColumnCellClick事件:

CellContentClick

如果处理void grid_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0) return; //I suposed you want to handle the event for column at index 1 if (e.ColumnIndex == 1) MessageBox.Show("Clicked!"); } ,则在使用图像列时应完全单击图像。

<强>截图

结果如下。第一列是显示图像的按钮列,第二列是设置为显示单个图像的普通图像列:

enter image description here