【发布时间】:2011-10-02 12:11:13
【问题描述】:
我想在 datagridviews 列中添加图像按钮。我用 datagridviewbuttonColumn 添加了 datagridview 但我没有将图像设置为此。我想在 datagridviews 列中添加带有按钮的图像,然后单击此按钮 datagridview 行编辑或删除。请问我该怎么做!
【问题讨论】:
标签: c# winforms datagridview imagebutton
我想在 datagridviews 列中添加图像按钮。我用 datagridviewbuttonColumn 添加了 datagridview 但我没有将图像设置为此。我想在 datagridviews 列中添加带有按钮的图像,然后单击此按钮 datagridview 行编辑或删除。请问我该怎么做!
【问题讨论】:
标签: c# winforms datagridview imagebutton
您可以使用从 DataGridViewImageButtonCell 类继承的自定义 DataGridViewImage 类,如下所示
public class DataGridViewImageButtonDeleteCell : DataGridViewImageButtonCell
{
public override void LoadImages()
{
// Load them from a resource file, local file, hex string, etc.
}
}
另外,请检查this 主题
【讨论】:
虽然DataGridView 有ButtonColumn,但它不直接提供显示图像的方式。
以下链接可能会指导您逐步完成任务:
DataGridView Image Button Cell
希望这会有所帮助...
【讨论】:
只需创建带有图像列的数据表并将图像添加到其中
dtMain.Columns.Add("ImageColumn", typeof(Image));
dtMain.Rows.Add(Image.FromFile(photopath + "1.jpg"));
然后在事件dataGridViewMain_CellContentClick上编写如下代码
if (e.ColumnIndex == dataGridViewMain.Columns["ImageColumn"].Index)
{
lblShowCellData.Text = dataGridViewMain.Rows[e.RowIndex].Cells["CustomerName"].Value.ToString();
// Do some thing else....
}
【讨论】:
可以在 asp:ButtonColumn 的 Text-Property 中提供 HTML。所以你实际上可以这样做:
<asp:ButtonColumn Text="<img src='icons/delete.gif' border='0' title='Delete entry' >" CommandName="delete"></asp:ButtonColumn>
呈现如下(HTML):
<td>
<a href="...">
<img src='icons/delete.gif' border='0' title='Delete entry' />
</a>
</td>
【讨论】:
实现此目的的一种方法是简单地覆盖 DataGridViewButtonCell 中的 Paint 方法,并从 graphics 参数中调用 DrawImage。调用必须发生在在碱基调用之后。
public class DeleteCell : DataGridViewButtonCell {
Image del = Image.FromFile("..\\..\\img\\delete.ico");
protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
{
base.Paint(graphics, clipBounds, cellBounds, rowIndex, elementState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
graphics.DrawImage(del, cellBounds);
}
}
之后只需创建自己的 DataGridViewButtonColumn,并将创建的 DeleteCell 设置为单元格模板:
public class DeleteColumn : DataGridViewButtonColumn {
public DeleteColumn() {
this.CellTemplate = new DeleteCell();
this.Width = 20;
//set other options here
}
}
就是这样。现在为您的 DataGridView 使用 DeleteColumn:
dgvBookings.Columns.Add(new DeleteColumn());
如果按钮点击的结果动作依赖于单元格行,请确保正确处理点击,即捕捉单元格行索引。
【讨论】: