[英]Getting System.FormatException while trying to cast
我有一个函数可以在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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.