首页 > 解决方案 > 文本框不返回 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

到底是怎么回事?

标签: c#textbox

解决方案


KeyPress 和 KeyDown 事件将在添加新按下的字符TextBox.Text之前调用,如果e.handle为 false,则新字符将添加到TextBox.Text并调用TextBox.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());
}

推荐阅读