我试图通过相应列的值类型来验证datagridview的输入,这是我的代码:如何验证c#中列值类型的datagridview输入?
private void dgvLoadTable_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
foreach (DataGridViewRow dr in dgvLoadTable.Rows)
{
foreach (DataGridViewCell dc in dr.Cells)
{
if (dc.GetType() == typeof(Int32) || dc.GetType() == typeof(Double))//if(dc.ColumnIndex==0)
{
DataGridViewTextBoxCell cell = dgvLoadTable[e.ColumnIndex, e.RowIndex] as DataGridViewTextBoxCell;
if (cell != null)
{
char[] chars = e.FormattedValue.ToString().ToCharArray();
foreach (char c in chars)
{
if (char.IsDigit(c) == false)
{
MessageBox.Show("You have to enter digits only");
e.Cancel = true;
break;
}} }
}
}
}
}
但是这是行不通的,应该是什么的一些列的类型?仅供参考,这是一个winForm应用程序,不同的数据通过用户选择在运行时在datagridview中加载。所以列以前不知道。 datagridview绑定到实体模型。
当然有很多种尝试/检查类型的方法。取决于你想要测试的是什么, – SebSky 2014-11-21 14:10:44
不能使用列索引或名称,因为哪个表将被加载到数据网格中是事先不知道的。我有10 +表,他们根据用户选择加载。 – Paradox 2014-11-21 14:35:53
是的,但使用上面你正在验证某些单元格不是整个表...然后,您可以使用http://stackoverflow.com/a/894296/4123158检查值是否为“数字” – SebSky 2014-11-24 09:36:31