【问题标题】:Change value of row to image based on cell value根据单元格值将行的值更改为图像
【发布时间】:2016-07-14 05:46:01
【问题描述】:

大家好,我正在做一个在 Visual Studio 2005 中创建的 Windows 窗体,它在 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

【问题讨论】:

  • 为什么要使用For .. Next循环?我很确定嵌套的 if 正在做你所期望的。
  • 我尝试在我的 datagridview 中循环这些值,但是当我没有使用循环时,结果仍然相同。值为 1 的单元格不显示为绿色
  • 试试这个:e.CellStyle.BackColor = If(e.Value=0, Color.Red, Color.Green) inside CellFormatting 事件。
  • 但我需要放的是图像而不是背景颜色。

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


【解决方案1】:

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

  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
      

样本数据:

 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

结果:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-09-29
    • 1970-01-01
    • 2014-07-20
    • 2018-08-15
    • 1970-01-01
    • 2023-04-06
    相关资源
    最近更新 更多