Merging Image and text in a single gridview cell
Neither you can add image in DataGridViewTextBoxColumn nor you can add text in DataGridViewImageColumn so merging text and image in the same cell in datagridview is bit tricky. To achieve this you can create your own control inheriting from “DataGridViewTextBoxColumn” and overriding paint method. Or you can track the grid view’s paint event and write the below functionality
Private Sub GridView1_Paint(ByVal sender As System.Object, ByVal e As System.Windows.Forms.PaintEventArgs) Handles GridView1.Paint
Dim count As Integer = 0
Dim xCordinate As Integer = _
GridView1.GetColumnDisplayRectangle(GridView1.Columns(“column1”).Index, True).X + 11
1. For count = GridView1.FirstDisplayedScrollingRowIndex To (GridView1.FirstDisplayedScrollingRowIndex + 7)
2. If count < GridView1.Rows.Count Then
3. Dim rct As Rectangle = GridView1.GetRowDisplayRectangle(count, True)
4. Dim rct2 As New Rectangle(xCordinate, rct.Y, 26, 25)
5. e.Graphics.DrawImageUnscaledAndClipped(My.Resources.Image1, rct2)
End If
Next
End Sub
Here are the details of steps mentioned above
1. Looping thorough the rows which comes under visible area. Here in the sample code we have 8 rows visible at a time rest are coming under horizontal scroll. So we loop through only those rows starting from “FirstDisplayedScrollingRowIndex “ and paint cell with an added image.
3. Get the rectangle dimension of each row. This is to set the y coordinate of each image we are going to paint manually
4. Get the rectangle dimension of the area under which we want to paint the image.
Here the left coordinate of rct2 is set by taking the X coordinate of the DataGridViewTextBoxColumn under which we are going to paint the image and adding 11 pixels to accommodate the text.
Y coordinate is the Y coordinate of each row
Width and height of rct2 is the dimension of the image we are going to paint
5. “DrawImageUnscaledAndClipped” draws the image without scaling it and clipped by the rectangle passed as a second parameter
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.


Comments
No comments yet.
Leave a comment