正文

在VB2005中根据内容改变datagridview单元格颜色2006-11-11 11:32:00

【评论】 【打印】 【字体: 】 本文链接:http://blog.pfan.cn/iamben250/20195.html

分享到:

This blog, and the source code it provides, demonstrate how to handle the Windows Forms DataGridView CellFormatting event to set the BackColor of a cell based on the cell's value.

The example application in the source code provides users a way to mark inactive customers and/or customers who have not placed an order in the last 30 days.

The CellFormatting event occurs when the contents of a cell in a Windows Forms DataGridView control needs to be formatted for display.

To set the BackColor of a cells based on their values, create a CellFormatting event handler. Within the handler add code to set the BackColor of individual cells based on their value.

Code Example

    1 Private Sub customerDataGridView_CellFormatting(ByVal sender As Object, ByVal e As DataGridViewCellFormattingEventArgs) Handles customerDataGridView.CellFormatting

    2 

    3     ' If the column being formatted is the column named 'Status' ..

    4     If Me.customerDataGridView.Columns(e.ColumnIndex).Name = "Status" Then

    5         If e.Value IsNot Nothing Then

    6             ' If the value of the cell is "Inactive" AND this form's inactiveCustomersCheckBox control is checked..

    7             If e.Value.ToString = "Inactive" And Me.inactiveCustomersCheckBox.Checked Then

    8                 ' Set the BackColor of the cell to yellow.

    9                 e.CellStyle.BackColor = Color.Yellow

   10             End If

   11         End If

   12     End If

   13 

   14     ' If the column being formatted is the column named 'LastOrderDate'..

   15     If Me.customerDataGridView.Columns(e.ColumnIndex).Name = "LastOrderDate" Then

   16         If e.Value IsNot Nothing Then

   17             ' If LastOrderDate was more than 30 days ago AND this form's ordersOverdueCheckBox control is checked..

   18             If Date.Now.Subtract(CType(e.Value, Date)).Days > 30 And Me.orderOverdueCheckBox.Checked Then

   19                 ' Set the BackColor of the cell to yellow-green.

   20                 e.CellStyle.BackColor = Color.YellowGreen

   21             End If

   22         End If

   23     End If

   24 End Sub

The CellFormatting event occurs every time each cell is painted, so you should avoid lengthy processing when handling this event.

For more information visit the link below:

DataGridView.CellFormatting Event

Click the link above to download Visual Basic source code in a Visual Studio 2005 solution which demonstrates how to handle the Windows Forms DataGridView CellFormatting event to set the BackColor of a cell based on the cell's value.

阅读(6894) | 评论(0)


版权声明:编程爱好者网站为此博客服务提供商,如本文牵涉到版权问题,编程爱好者网站不承担相关责任,如有版权问题请直接与本文作者联系解决。谢谢!

评论

暂无评论
您需要登录后才能评论,请 登录 或者 注册