[英]Change the row color in DataGridView based on the quantity of a cell value
[英]Change value of row to image based on cell value
大家好,我正在做一個在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
您的問題有幾種解決方案,我將提供其中一種。
您在DataGrid
需要兩列。
一種是保存原始數據(0或1);另一種是保存原始數據。 在我的示例中,我將其稱為colValue
。
另一種是僅保留圖像(紅色或綠色); 名為colImg
。
colValue
未顯示在網格中:
'Set colValue invisible which is first column in my example DataGridView1.Columns(0).Visible = False
使用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
為了避免在初始化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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.