簡體   English   中英

嘗試投射時獲取System.FormatException

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM