我有一个用户将修改的数据网格。一列存储 Single preciion float 。当用户输入超过 7 位数字时,该数字将以科学计数法显示,与该数字的比较变得非常不准确。我想警告用户,发生这种情况时,该号码只会被近似存储。有没有什么办法可以确定一个数字什么时候可以正确存储在一个单一的?截止值似乎约为 7 位数。除此之外,它还有很长的路要走。
请您参考如下方法:
我认为您需要对每个单元格进行验证。
逐步解释:
通过设计器或代码将 CellValidating 事件添加到 DataGridView:
dataGridView1.CellValidating+=dataGridView1_CellValidating;
检查你是否想要像这样:
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
double value = 0;
if (double.TryParse(e.FormattedValue.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "";
// e.Cancel = false;
}
else
{
dataGridView1[e.ColumnIndex, e.RowIndex].ErrorText = "Bad Input Please Correct It !";
// e.Cancel = true; if you do this the datagrid dont let user go next row
}
}
如果你想更正你自己的值(value)也做这些步骤:
也添加 CellValidated 事件:
dataGridView1.CellValidated+=dataGridView1_CellValidated;
然后检查一下:
private void dataGridView1_CellValidated(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1[e.ColumnIndex, e.RowIndex].Value == null)
return;
double value = 0;
if (double.TryParse(dataGridView1[e.ColumnIndex,e.RowIndex].Value.ToString(), System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.InvariantCulture, out value))
{
dataGridView1[e.ColumnIndex, e.RowIndex].Value = Math.Round(value, 2).ToString().Replace("/",".");
}
}
注意: 每次单元格编辑时都会发生此事件,如果您想在特殊单元格上执行这些操作,请在事件引发之前检查它。您可以为每列设置最大输入长度以避免输入错误。
