简体   繁体   中英

Change value of row to image based on cell value

Hi everyone i am doing a windows form which is created in visual studio 2005, wherein it displays data in datagridview. I have a column "colImg" that will display 1 and 0. But i need to display a red image when the value of cell of colImg is 0 and green image when the value is 1. I have a code but the problem is it only displays image which is green but i have a values which is 0. Is there any problem on my code?

Private Sub grdView_CellFormatting(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellFormattingEventArgs) Handles grdView.CellFormatting
    If grdView.Columns(e.ColumnIndex).Name.Equals("colImg") Then
        Dim value As Integer
        If TypeOf e.Value Is Integer Then
            value = DirectCast(e.Value, Integer)
            e.Value = My.Resources.Resources.NotYet
        Else
            For i As Integer = 0 To grdView.RowCount
                If value = 0 Then
                    e.Value = My.Resources.Resources.Red

                Else
                    e.Value = My.Resources.Resources.Green
                End If
            Next

        End If
    End If

There are several solutions for your question, I will provide one of them.

  1. You need two columns in your DataGrid .
    One is to hold the raw data (0 or 1); in my example I called it colValue .
    The other is to hold only the image (red or green); named colImg .
    colValue is not shown in the grid :

     'Set colValue invisible which is first column in my example DataGridView1.Columns(0).Visible = False 
  2. Use the CellValueChanged event to set the image of the colImg cell:

     If e.ColumnIndex = 0 AndAlso Not isInit Then 'Value column has changed and we are not in Form Initializing Dim valueCell = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex) Dim imgCell = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex + 1) 'Whatever index your colImg is If Integer.Parse(valueCell.Value.ToString()) = 1 Then imgCell.Value = My.Resources.Green Else imgCell.Value = My.Resources.Red End If End If 
    1. To avoid that the event code breaks when the Form and thus the DataGridView is being initilized I created a local variable isInit and set it before and after the initialization:

       Public Class Form1 Private isInit As Boolean Public Sub New() isInit = True InitializeComponent() isInit = False ... End Sub ... End Class 

Sample Data:

 DataGridView1.Rows(0).Cells(0).Value = 1
 DataGridView1.Rows(1).Cells(0).Value = 0
 DataGridView1.Rows(2).Cells(0).Value = 0
 DataGridView1.Rows(3).Cells(0).Value = 1

Outcome:
在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM