C# 在不移动光标的情况下修改文本框
我写了一个复选框,限制用户在文本框中输入的权重字段不超过一个小数位C# 在不移动光标的情况下修改文本框,c#,winforms,C#,Winforms,我写了一个复选框,限制用户在文本框中输入的权重字段不超过一个小数位 private void txtWeight_TextChanged(object sender, EventArgs e) { decimal enteredWeight; if (Decimal.TryParse(txtWeight.Text, out enteredWeight)) { decimal roundedWeight = RoundDown(enteredWeight,
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()
是无关紧要的)
我的问题是,在用户输入小数点后的第二个数字后,它会很好地将其删除,但光标会移动到字段的开头
e、 g
之前:69.2 |
然后键入a 4(例如,69.24
,这是不允许的)
之后:| 69.2
我希望文本框中的光标保持在它所在的位置。。。可以这样做吗?试试:
txtWeight.CaretIndex = txtBox.Text.Length;
或:
加:
您可以保存插入符号的位置,然后在更改文本后重新设置
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;
}
}
}
你说“光标”的意思可能是“插入符号”?@UweKeim好的。。。但除了
^
符号之外,我从未听说过这个词。。。有什么区别?我指的是一条闪烁的线,它指示下一个字符将到达我的位置“cursor”表示“mouse cursor”。“插入符号”表示“文本光标”。根据你的链接,这两个词都是正确的!我知道;-)我只是想确定你的问题与文本光标(又名“插入符号”)有关,而不是鼠标光标。这不是WPF唯一的属性吗?@UweKeim是的,我知道。这就是我问的原因。用户将其问题标记为winforms
,而不是wpf
。但不管插入符号之前在哪里,它都会将其始终放在字段的末尾。。。
txtWeight.Select(txtWeight.Text.Length - 1,0)
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;
}
}
}