DataGridView图像按钮列

thi*_*zar 6 c# datagridview imagebutton winforms

我想在datagridviews列中添加图像按钮.我使用datagridviewbuttonColumn添加了datagridview,但是我没有将图像设置为this.我想在datagridviews列中添加带按钮的图像,当单击此按钮时,datagridview行编辑或删除.请问我该怎么做!

Ted*_*dK. 6

可以实现的一种方法是简单地从DataGridViewButtonCell重写Paint方法,并从图形参数调用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);
        }
    }
Run Code Online (Sandbox Code Playgroud)

之后,只需创建自己的DataGridViewButtonColumn,并将创建的DeleteCell设置为单元格模板:

public class DeleteColumn : DataGridViewButtonColumn {
        public DeleteColumn() {
            this.CellTemplate = new DeleteCell();
            this.Width = 20;
            //set other options here 
        }
    }
Run Code Online (Sandbox Code Playgroud)

而已.现在使用DeleteColumn为您的DataGridView:

dgvBookings.Columns.Add(new DeleteColumn());
Run Code Online (Sandbox Code Playgroud)

如果按钮单击的结果操作取决于单元格行,请确保正确处理单击,即捕获单元格行索引.


Dul*_*ttu 3

虽然DataGridViewButtonColumn它并不直接提供显示图像的方式。

以下链接可以指导您逐步完成任务:

DataGridView 图像按钮单元格

希望这可以帮助...