简体   繁体   中英

Getting System.FormatException while trying to cast

I have a function to duplicate a row in DataGridView which looks like this:

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;
    }
}

Now i wanted to write a function for one specific cell to increase + 1 with every click. For example: if in Cell[2] the value is 1, with the next added row the value should count up to 2, 3 and so on. I´ve tried to operate with + but i´ve got a error message that the operator cannot be applied to type of object. So i´ve tried to cast the specific cell like this:

 var value2 = Convert.ToInt32(dgv.Rows[e.RowIndex].Cells[2].Value);

But now i get a SystemFormatException: Input string was not in a correct format. Any ideas?

Many thanks in advance!

Allow only numeric values as below

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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM