根据单元格值更改行到图像的值

时间:2016-07-14 05:46:02

标签: vb.net datagridview visual-studio-2005

大家好我正在做一个在visual studio 2005中创建的窗体,它在datagridview中显示数据。我有一个专栏" colImg"这将显示1和0.但是当colImg的单元格的值为0时我需要显示红色图像,当值为1时我需要显示绿色图像。我有一个代码,但问题是它只显示绿色但我的图像有一个值为0.我的代码有什么问题吗?

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

1 个答案:

答案 0 :(得分:0)

您的问题有几个解决方案,我将提供其中一个。

  1. DataGrid中需要两列 一种是保存原始数据(0或1);在我的例子中,我称之为colValue 另一种是只保留图像(红色或绿色);名为colImg
    网格中未显示colValue

    'Set colValue invisible which is first column in my example
    DataGridView1.Columns(0).Visible = False
    
  2. 使用CellValueChanged事件设置colImg单元格的图像:

    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. 为了避免在FormDataGridView被启动时事件代码中断,我创建了一个局部变量isInit并在初始化之前和之后设置它:

      Public Class Form1
      
        Private isInit As Boolean 
      
        Public Sub New()
            isInit = True
            InitializeComponent()
            isInit = False
            ...
       End Sub
        ...
      End Class
      
  3. 示例数据:

     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
    

    结果:
    enter image description here