Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGridView Image Button Column

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!

like image 810
thinzar Avatar asked Jul 11 '11 04:07

thinzar


1 Answers

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.

like image 134
TedK. Avatar answered Sep 24 '22 00:09

TedK.