c# - 尝试投射时获取 System.FormatException
问题描述
我有一个在 DataGridView 中复制一行的功能,如下所示:
private void dgv_CellClick(object sender, DataGridViewCellEventArgs e)
{
DataGridView dgv = sender as DataGridView;
// If button clicked
if (e.ColumnIndex == 0)
{
// Get values what you want to use
var value1 = dgv.Rows[e.RowIndex].Cells[1].Value;
var value2 = dgv.Rows[e.RowIndex].Cells[2].Value;
// Insert a new row behind the click one
dgv.Rows.Insert(e.RowIndex + 1);
// Set the previously stored values
dgv.Rows[e.RowIndex + 1].Cells[1].Value = value1;
dgv.Rows[e.RowIndex + 1].Cells[2].Value = value2;
}
}
现在我想为一个特定的单元格编写一个函数,每次点击都会增加 + 1。例如:如果在 Cell[2] 中值为 1,则在下一个添加的行中,该值应计数为 2、3 等等。我尝试使用 + 进行操作,但我收到一条错误消息,指出该运算符不能应用于对象类型。所以我试图像这样投射特定的单元格:
var value2 = Convert.ToInt32(dgv.Rows[e.RowIndex].Cells[2].Value);
但现在我得到一个 SystemFormatException:输入字符串的格式不正确。有任何想法吗?
提前谢谢了!
解决方案
只允许如下数值
private void dgv_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
// Textbox columns
if (dgv.CurrentCell.ColumnIndex == 2)
{
TextBox tb = e.Control as TextBox;
if (tb != null)
{
tb.KeyPress += TextBox_KeyPress;
}
}
}
private void TextBox_KeyPress(object sender, KeyPressEventArgs e)
{
// Only numeric characters allowed
if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
{
e.Handled = true;
}
}
推荐阅读
- java - 摆动丢失异常
- java - 嗨,我可以在他或她在线时显示用户状态吗?反之亦然,在 android 中使用 firebase 可以显示用户状态吗?
- selenium - 从另一个 @Test 方法调用时如何在 TestNG 报告中显示 @Test 结果。请提出答案
- javascript - 拆分JS字符串正则表达式大写后跟小写
- java - Java 线程和异常处理
- python - Django - 在进程运行时显示 shell 输出命令
- azure-service-fabric - 在无状态服务的所有活动实例上调用相同的方法
- excel - IF Then 语句中的 VBA 数组公式和目标搜索
- javascript - TypeError:在未实现接口位置的对象上调用了“分配”
- yii2 - Yii2 唯一验证者加入错误