DataGridView使用技巧十:单元格表示值的自定义

通过CellFormatting事件,可以自定义单元格的表示值。(比如:值为Error的时候,单元格被设定为红色)

示例:

 1 private void dgv_Users_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
 2         {
 3             try
 4             {
 5                 if (e == null || e.Value == null || !(sender is DataGridView))
 6                     return;
 7                 DataGridView dgv = sender as DataGridView;
 8                 if (dgv.Columns[e.ColumnIndex].Name=="Sex")
 9                 {
10                     string value = e.Value.ToString();
11                     if (value.Equals(""))
12                     {
13                         e.Value = "Woman";
14                         e.FormattingApplied = true;
15                     }
16                 }                
17             }
18             catch (Exception ex)
19             {
20                 MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
21             }
22         }

 

posted @ 2017-05-07 09:44  .NET开发菜鸟  阅读(907)  评论(0编辑  收藏  举报