显示图像在按钮
您可以添加一个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;
}
}
显示图像,而按钮
要显示所有列的单个图像,包括新行,您可以设置DataGridViewImageColumn
的Image
财产。这样,图像将在该列显示在所有行中:如果你可能想为细胞不同的图像
dataGridView1.Columns.Add(new DataGridViewImageColumn(){
Image = Properties.Resources.SomeImage, Name = "someName", HeaderText = "Some Text"
});
此外,您还可以在CellFormatting
事件设置的DataGridViewImageColumn
格式化的值:
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;
}
您还可以将DataGridViewImageColumn
的Image
属性设置为图像,但图像不会显示在新行上。
手柄点击
要处理点击图片/按钮,您可以处理CellClick
或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!");
}
如果处理CellContentClick
你应该对图像准确点击,当你使用image列。
截图
下面是结果。第一列是示出图像和第二列的按钮列是一个正常的图像列设定为显示单个图像:
![enter image description here](https://i.stack.imgur.com/QFXQe.png)
http://www.codeproject.com/KB/grid/DGV_ImageButtonCell.aspx – MethodMan
所以,当你说它没有正确显示时,它是否根本没有出现?它显示,但显示器有问题吗? – Jace
我已经尝试了各种可以找到的示例代码。我最终会看到一个没有标签的灰色按钮,或者是一个灰色的按钮,上面写着windows.system.bitmap。当我按下按钮来调用启动/停止服务的功能时,我也无法解决问题。 – Brad