c# - 文本框不返回 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
到底是怎么回事?
解决方案
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());
}
推荐阅读
- bash - 在bash中将文件名修剪为给定数量的字母的命令
- shell - npx:shell-auto-fallback 参数已被删除
- python - 当两者之一是 np.array(dtype=np.complex128).real 时,numpy matmul 非常慢
- javascript - 从输入类型 = 文件中选择图像并使用样式组件将其设置为背景
- firebase - Firebase Admin SDK 不读取、写入或抛出错误 (Node.js)
- java - 触发更新后应用程序销毁后通知被解除
- postgresql - 在 Postgres 中手动插入 UUID 值的语法
- c++ - 以不可预测的顺序从字符串生成相同的哈希 C++
- bluetooth - BLUETOOTH - Linux:使用 bluetoothctl 更改外观广告失败
- excel - 需要excel公式来编译没有特定标识符的数据