在Windows窗体中当我在文本框中单击退格时错误消息即将到来 [英] In Windows Forms When I Am Clicking Backspace In Textbox Error Msg Is Coming

查看:47
本文介绍了在Windows窗体中当我在文本框中单击退格时错误消息即将到来的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

if(!char.IsDigit(e.KeyChar))

{

lblfphnoin.Text =请仅输入数字;

e.Handled = true;

}

当我点击文本框中的空格时,它显示错误信息。但我想清除最后输入的字符或数字,焦点必须在同一个文本框中最后清除的文本。 [windows窗体]

if (!char.IsDigit(e.KeyChar))
{
lblfphnoin.Text = "pls enter only digits";
e.Handled = true;
}
when i am clicking back space in textbox it is showing above error msg. but i want to clear last entered character or digit and focus must be in same textbox last cleared text.[windows forms]

推荐答案

那是因为你丢弃所有其他打字而不是数字。你也必须考虑退格。

尝试:

That is because you discard every other typing than digits. You have to take account of the backspace also.
Try:
if (!char.IsDigit(e.KeyChar) && (e.KeyChar != '\b'))





希望这会有所帮助。



Hope this helps.


为什么不这样做?!

您的代码检查仅数字键,退格键不是其中之一...

您有三个选项

1.使用 NumericUpDown [ ^ ]控制(如果适合)

2.使用验证 [ ^ ]事件检查文本框值

3.编写代码正确...请查看此示例: https ://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v = vs.110).aspx [ ^ ]
Why should not?!
Your code checks for digit-only keys, backspace is not one of them...
You have three options
1. Use NumericUpDown[^] control (if that fits in)
2. Use the Validating[^] event to check the text-box value
3. Write your code correctly...Check this sample: https://msdn.microsoft.com/en-us/library/system.windows.forms.control.keypress(v=vs.110).aspx[^]


使用SelectionStart和SelectionLength属性。

如果Selection Length为零,则Selection start是文本字符串中光标位置的索引,所以string.Remove将为你删除角色。

如果它不为零,则有一个选择,你需要删除整个东西:

Use the SelectionStart and SelectionLength properties.
If Selection Length is zero, then the Selection start is the index of the cursor position in your text string, so a string.Remove will remove the character for you.
If it is non-zero, there is a selection, and you need to remove the whole thing:
int selStart = SelectionStart;
int selLength = SelectionLength;
if (char.IsControl(e.KeyChar))
    {
    if (e.KeyChar == '\b')
        {
        // Backspace
        if (selLength > 0)
            {
            myTextBox.Text = myTextBox.Text.Remove(selStart, selLength);
            SelectionLength = 0;
            SelectionStart = selStart;
            }
        else if (selStart > 0)
            {
            myTextBox.Text = myTextBox.Text.Remove(selStart - 1, 1);
            SelectionStart = selStart - 1;
            }
        e.Handled = true;
        }
    }


这篇关于在Windows窗体中当我在文本框中单击退格时错误消息即将到来的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆