按钮列的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";
如果最好使用一个图像按钮或一个可点击的图像,我就无法解决。 我也无法正确显示按钮。
谢谢Brad
在按钮上显示图像
您可以添加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列时应该完全单击图像。
截图
这是结果。 第一列是显示图像的按钮列,第二列是设置为显示单个图像的普通图像列: