2016-07-14 21 views
0

こんにちは皆私はVisual Studio 2005で作成されたウィンドウフォームを行っています。そこではデータグリッドビューにデータが表示されます。私は1と0を表示する列 "colImg"があります。しかし、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 
+0

は、なぜあなたは使用しない '..についてはNext'ループ?ネストされた 'if'が期待していることをやっていることは確かです。 –

+0

私は自分のdatagridviewでそれらの値をループしようとしましたが、私はループを使用しなかったとき、結果は同じです。値が1のセルは緑色で表示されません – Jan

+0

これを試してください: 'CellFormatting'イベントの' e.CellStyle.BackColor = If(e.Value = 0、Color.Red、Color.Green) ' –

答えて

0

あなたの質問にはいくつか解決策がありますが、そのうちの1つを提供します。

  1. DataGridには2つの列が必要です。
    1つは、生データ(0または1)を保持することです。私の例では、私はそれをcolValueと呼んだ。
    もう1つは画像(赤または緑)のみを保持することです。 colImgという名前です。
    colValueがグリッドには示されていない。

    'Set colValue invisible which is first column in my example 
    DataGridView1.Columns(0).Visible = False 
    
  2. colImg細胞の画像を設定するCellValueChangedイベントを使用:

    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 
    
  3. 避けるためにForm、したがってDataGridViewが初期化されているときにイベントコードが壊れていることを確認します。ローカル変数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 

結果:
enter image description here

関連する問題