我写了一个检查来限制用户在文本框中输入的重量字段不超过一位小数。
private void txtWeight_TextChanged(object sender, EventArgs e)
{
decimal enteredWeight;
if (Decimal.TryParse(txtWeight.Text, out enteredWeight))
{
decimal roundedWeight = RoundDown(enteredWeight, 1);
if (enteredWeight != roundedWeight)
{
txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");
}
}
}
(RoundDown()
的实现无关紧要)
我的问题是,在用户输入小数点后的第二个数字后,它会很好地删除它,但光标会移动到字段的开头。
例如
之前:69.2|
然后输入 4(例如 69.24
,这是不允许的)
之后:|69.2
我希望文本框中的光标保持在原来的位置...这可以做到吗?
最佳答案
您可以保存插入符号的位置,然后在更改文本后重新设置它。
private void txtWeight_TextChanged(object sender, EventArgs e)
{
decimal enteredWeight;
if (Decimal.TryParse(txtWeight.Text, out enteredWeight))
{
decimal roundedWeight = RoundDown(enteredWeight, 1);
if (enteredWeight != roundedWeight)
{
int caretPos = txtWeight.SelectionStart;
txtWeight.Text = RoundDown(enteredWeight, 1).ToString("F1");
txtWeight.SelectionStart = caretPos;
}
}
}
关于c# - 不移动光标修改文本框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33262657/