我写了一张支票,以限制用户在文本框中输入一个不超过小数位的权重字段。
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;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句