c# - 写入符号/字母时出现 DataGridView 错误 System.FormatException
问题描述
我有以下 DataGridview 只需要写入整数,但是如果用户写入任何符号/字母,则会提示此错误。顺便说一句,此列是从数据库加载的,并且值将始终是整数(因此整个列仅用于数字),因此我不知道在用户编辑行时如何验证数字并且不显示此错误。
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.Rows[e.RowIndex].Cells[5].Value != null)
{
if (dataGridView1.Rows[e.RowIndex].Cells[5].Value == System.DBNull.Value || dataGridView1.Rows[e.RowIndex].Cells[5].Value == null)//Check if cell is not nulll
{
dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.White;
}
else
{
int numero;
string mimonto = string.Empty + this.dataGridView1.Rows[e.RowIndex].Cells[5].Value;
bool res = true;
for (int i = 0; i < mimonto.Length; i++)
{
if (char.IsNumber(mimonto[i]) == true)// if position is a number
{
}
else
{
res = false;//value is not a number
}
}
if (res == true)
{
dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.White; //this is a number and color stays as white
}
else
{
dataGridView1.Rows[e.RowIndex].Cells[5].Style.BackColor = Color.Red;//color is red if it's not a number
dataGridView1.Rows[e.RowIndex].Cells[5].Value = 0;
MessageBox.Show("Debe ingresar valores númericos");
}
}
}
}
这是符号/字母或任何非数字的错误。
顺便说一句,是否有任何选项可以仅在单元格上启用数字写入?或者有没有更好的选择来解决这个错误?
解决方案
推荐阅读
- cordova - iOS平台ionic-3中的离子输入问题
- django - django-rest-framework 在使用外键访问另一个模型时在模型中引发错误
- java - TreeMap 和 SortedMap 转换语句
- javascript - 休息api jqgrid
- docker - 无法安装asp.net核心开发证书工具(dev-certs)
- php - 如何使用php从键值对中的多维数组中回显值
- spring - 如何使用 Spring Boot WebClient 收集分页 API 响应?
- javascript - 如何在jquery上动态添加数字顺序
- openshift - CLI 监控 OpenShift 中的连接池
- android - 如何用 FusedLocationProviderClient 替换 FusedLocationApi?