C# - DataGridView - Image and Text on the same row

Viewed 16226

I am looking for something like this on DataGridView:

Image  | Text | 
Text   | Text |
Image  | Text

Basically, I just want Image cells and Text cells on the same row. I was able to get it to work with different types, for example: Checkbox, Text, and etc... But I am not able to get it to work with images.

I get this error: Invalid Cast from 'System.String' to 'System.Drawing.Image'

Does anybody know the solution or have suggestion on how I should do this ? Thanks

3 Answers

For better solution, Please refer this Blogspot post.

I tried the same solution for my project, it is working well, to display 16X16 pixels image in my datagrid cell, I have edited the function in above TextandImageColumn class:

protected override void Paint(Graphics graphics, Rectangle clipBounds,
    Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState,
    object value, object formattedValue, string errorText,
    DataGridViewCellStyle cellStyle,
    DataGridViewAdvancedBorderStyle advancedBorderStyle,
    DataGridViewPaintParts paintParts)
    {
        // Paint the base content
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState,
           value, formattedValue, errorText, cellStyle,
           advancedBorderStyle, paintParts);

        if (this.Image != null)
        {
            PointF p = cellBounds.Location;
            p.X += 0;
            p.Y += 4;

            graphics.DrawImage(this.Image, p);
        }
    }
Related