C# DataGrid单元格编辑完成后检查单元格格式,如果格式不对则取消被检查单元格的编辑
时间: 2023-12-12 16:02:22 浏览: 45
你可以使用 DataGrid 的 CellEndEdit 事件来检查单元格格式,如果格式不正确,则可以使用 CancelEdit 方法取消编辑。
以下是一个示例代码:
```
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
DataGridViewCell cell = dataGridView1[e.ColumnIndex, e.RowIndex];
if (cell.Value != null && cell.Value.ToString() != "")
{
// 检查单元格格式
if (!CheckCellFormat(cell.Value.ToString()))
{
cell.ErrorText = "格式不正确";
dataGridView1.CancelEdit();
}
else
{
cell.ErrorText = "";
}
}
}
private bool CheckCellFormat(string value)
{
// 检查单元格格式的代码
// 如果格式正确返回 true,否则返回 false
}
```
在上面的代码中,CheckCellFormat 方法用于检查单元格格式,如果格式不正确则返回 false。在 CellEndEdit 事件中,如果单元格的值不为空,则调用 CheckCellFormat 方法检查单元格格式,如果格式不正确,则设置单元格的 ErrorText 属性为“格式不正确”,并调用 CancelEdit 方法取消编辑。如果格式正确,则清空单元格的 ErrorText 属性。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)