我有一个包含datgridview的
Windows窗体应用程序.我需要在datagridview单元格上强制执行单元格验证,以便它不接受负值.我从msdn库中找到了合适的代码.
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e) { dataGridView1.Rows[e.RowIndex].ErrorText = ""; int newInteger; // Don't try to validate the 'new row' until finished // editing since there // is not any point in validating its initial value. if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; } if (!int.TryParse(e.FormattedValue.ToString(),out newInteger) || newInteger < 0) { e.Cancel = true; dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer"; } }
不幸的是,代码只允许在datagridview中输入整数.由于我的列名称为“项目名称”,应该作为文本输入,因此代码中存在问题.当我输入项目名称时,它会生成一条错误消息.其余的单元格验证完全正常工作!我该怎么编辑代码,以免它产生这个错误?
提前致谢
Mirfath
解决方法
DataGridViewCellValidatingEventArgs e具有.ColumnIndex属性,您可以检查该属性以确保仅对您希望的列进行验证.
private void dataGridView1_CellValidating(object sender,DataGridViewCellValidatingEventArgs e) { if (e.ColumnIndex == dataGridView1.Columns["MyNumericColumnName"].Index) { dataGridView1.Rows[e.RowIndex].ErrorText = ""; int newInteger; // Don't try to validate the 'new row' until finished // editing since there // is not any point in validating its initial value. if (dataGridView1.Rows[e.RowIndex].IsNewRow) { return; } if (!int.TryParse(e.FormattedValue.ToString(),out newInteger) || newInteger < 0) { e.Cancel = true; dataGridView1.Rows[e.RowIndex].ErrorText = "the value must be a Positive integer"; } } }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。