簡體   English   中英

文本框不返回 Visual C# 中的當前值

[英]textbox doesn't return current value in visual C#

我正在嘗試將文本框的當前整數值立即放入整數,但使用以下代碼似乎我總是落后 1 步:

private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
    // Only allow nummeric value
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }

    if (txtMemoryLocation.Text != "")
    {
        nLocation = int.Parse(txtMemoryLocation.Text.Trim());
    }
}

我總是從文本框中的數字 1 開始,當我將“1”更改為“10”時,我的 nLocation 更改為 1,當我輸入“100”時,nLocation 變為 10

到底是怎么回事?

改為掛鈎 TextChanged 事件並在那里進行解析。 當 KeyDown、KeyPress 和 KeyUp 觸發時,文本框仍然沒有機會接受新字符。

或者,您可以將新按下的鍵包含在我修改現有函數中,如下所示:

private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
    // Only allow nummeric value
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
    {
        e.Handled = true;
    }

    if (txtMemoryLocation.Text != "")
    {
        nLocation = int.Parse(txtMemoryLocation.Text.Trim() + e.KeyChar);
    }
}

KeyPress 和 KeyDown 事件將在添加新按下的字符TextBox.Text之前調用,如果e.handle為 false,則新字符將添加到TextBox.TextTextBox.TextChanged將調用。

你可以像我一樣這樣做

注意:首先將 TextChanged 方法添加到 txtMemoryLocation.TextChanged

private void txtMemoryLocation_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar));
}
private void TextChanged(object sender,EventArgs e)
{
    nLocation = int.Parse(txtMemoryLocation.Text.Trim());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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