DataGridView Image Button Column

thinzar picture thinzar · Jul 11, 2011 · Viewed 28.2k times · Source

I want to add image button in datagridviews column . I added the datagridview with datagridviewbuttonColumn but I don't set the image to this . I want to add image with button in datagridviews column and when click this button datagridview row edit or delete. Please How do I do that!

Answer

TedK. picture TedK. · Dec 10, 2013

One way this can be achieved is to simply override Paint method from DataGridViewButtonCell and and call DrawImage form the graphics parameter. The call must occur after base call.

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);
        }
    }

After that simply create your own DataGridViewButtonColumn, and set created DeleteCell as the cell template:

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

That's it. Now use DeleteColumn for your DataGridView:

dgvBookings.Columns.Add(new DeleteColumn());

If the resulting action of button click depends on cell row, make sure to handle the clicks right, that is, to catch the cell row index.