Question Need help to set image on datagridview.

trialer

Well-known member
Joined
Oct 4, 2010
Messages
64
Programming Experience
1-3
'data of the datagridview

VB.NET:
        dgvSubs.Columns.Clear()              
        dgvSubs.Columns.Add("a", "a")
        dgvSubs.Columns.Add("b", "b")
        dgvSubs.Columns.Add("c", "c")


        Dim row As String() = New String() {"1", "Product 1", "1000"}
        dgvSubs.Rows.Add(row)
        row = New String() {"2", "Product 2", "2000"}
        dgvSubs.Rows.Add(row)
        row = New String() {"3", "Product 3", "3000"}
        dgvSubs.Rows.Add(row)
        row = New String() {"4", "Product 4", "4000"}
        dgvSubs.Rows.Add(row)


'Setting the image of the datagridview
VB.NET:
Dim imgColumn As New DataGridViewImageColumn


        With imgColumn
            .HeaderText = ""


        End With


        ' Add the img column to the control.
        dgvSubs.Columns.Insert(dgvSubs.Columns.Count, imgColumn)


        With dgvSubs
            Dim i As Integer


            For i = 0 To dgvSubs.Columns.Count - 1


                dgvSubs.Columns.Item(i).SortMode = DataGridViewColumnSortMode.Programmatic
            Next i


            For Each row As DataGridViewRow In .Rows
                If row.Cells(2).Value >= 2000 Then
                    imgColumn.Image = ImageList1.Images(0) 'Blue image
                ElseIf row.Cells(2).Value < 2000
                    imgColumn.Image = ImageList1.Images(1)  'Green image
                End If
            Next
        End With

how do i set the backgroud image of imgColumn if the value in c >= 2000 to blue and if the value in c < 2000 the background is green. I used imagelist.
 
A Column.Image is exactly that. The image which appears in every cell of a column. Simply load the images as you would any other data item.

            For Each row1 As DataGridViewRow In .Rows
                If CInt(row1.Cells(2).Value) >= 2000 Then 'datagridview items are not typed so this will otherwise be a string
                    row1.Cells(3).Value = ImageList1.Images(0)
                Else
                    row1.Cells(3).Value = ImageList1.Images(1)
                End If
            Next
 
how do i count the rows which contains image 1 and image 0?

To determine whether a row contains a specific image you need to check whether the Value of the appropriate cell in that row Is that Image object, e.g.
If row.Cells(3).Value Is ImageList1.Images(0) Then
You can use an If statement like that in a loop and count as you go or you can use a similar condition in a LINQ query to get the count in one line.
 
Back
Top