winform中dataGridView单元格根据值设置新值,彻底解决绑定后数据类型转换的困难

时间:2022-06-10 04:16:18

//

winform中dataGridView单元格在数据绑定后,数据类型更改困难,只能迂回实现。有时候需要将数字变换为不同的文字描述,就会出现int32到string类型转换的异常,借助CellFormatting事件就可以轻松解决了。

在dataGridView添加CellFormatting事件,如:dataGridView1_CellFormatting

参考代码:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
if (e.ColumnIndex == 3)
{
e.FormattingApplied = true; if (dataGridView1.Rows[e.RowIndex] != null && !dataGridView1.Rows[e.RowIndex].IsNewRow)
{
if (e.Value.ToString() == "0")
{
e.Value = "保存";
}
else if (e.Value.ToString() == "1")
{
e.Value = "提交";
}
else
{
e.Value = "";
}
} }
}