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

时间:2023-03-08 18:59:30
DataGridView使用技巧十:单元格表示值的自定义

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

示例:

 private void dgv_Users_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
try
{
if (e == null || e.Value == null || !(sender is DataGridView))
return;
DataGridView dgv = sender as DataGridView;
if (dgv.Columns[e.ColumnIndex].Name=="Sex")
{
string value = e.Value.ToString();
if (value.Equals("女"))
{
e.Value = "Woman";
e.FormattingApplied = true;
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace);
}
}