且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

DataGridView 单元格表示值的自定义

更新时间:2022-08-14 18:23:07

通过CellFormatting事件,可以自定义单元格的表示值。(比如:值为Error的时候,单元格被设定为红色)
下面的示例:将“Colmn1”列的值改为大写。

[VB.NET]
'CellFormatting 事件处理方法
Private Sub DataGridView1_CellFormatting(ByVal sender As Object, _
        
ByVal e As DataGridViewCellFormattingEventArgs) _
        
Handles DataGridView1.CellFormatting
    
Dim dgv As DataGridView = CType(sender, DataGridView)

    
如果单元格是“Column1”列的单元格
    If dgv.Columns(e.ColumnIndex).Name = "Column1" AndAlso _
            
TypeOf e.Value Is String Then
        
将单元格值改为大写
        Dim str As String = e.Value.ToString()
        e.Value = 
str.ToUpper()
        
'  应用该FormatFormat完毕。
        e.FormattingApplied = True
    
End If
End Sub

 

[C#]
//CellFormatting 事件处理方法
private void DataGridView1_CellFormatting(object sender,
    DataGridViewCellFormattingEventArgs e)
{
    DataGridView dgv = (DataGridView)sender;

    
// 如果单元格是“Column1”列的单元格
    if (dgv.Columns[e.ColumnIndex].Name == "Column1" && e.Value is string)
    {
        
// 将单元格值改为大写
        string str = e.Value.ToString();
        e.Value = str.ToUpper();
        
// 应用该FormatFormat完毕。
        e.FormattingApplied = true;
    }
}


CellFormatting
事件的DataGridViewCellFormattingEventArgs对象的Value属性一开始保存着未被格式化的值。当Value属性被设定表示用的文本之后,把FormattingApplied属性做为True,告知DataGridView文本已经格式化完毕。如果不这样做的话,DataGridView会根据已经设定的FormatNullValueDataSourceNullValueFormatProvider属性会将Value属性会被重新格式化一遍。




本文转自 qianshao 51CTO博客,原文链接:http://blog.51cto.com/qianshao/201795,如需转载请自行联系原作者