How to get the current text after each key press i

2019-08-09 10:49发布

I am trying to filter a list of items in a ListView as the user types into a TextBox and I use KeyDown, and KeyPress events but when I read the textbox.Text, it always returns the text before the last key press. Is there a way to always get whatever is shown in the TextBox without pressing enter?

6条回答
够拽才男人
2楼-- · 2019-08-09 11:23

You could use the TextChanged event of the TextBox in question. I think the KeyUp event might work as well.

查看更多
等我变得足够好
3楼-- · 2019-08-09 11:25
 public static string NextControlValue(string originalValue, int selectStart, int selectLength, string keyChar)
    {
        if (originalValue.Length > selectStart)
        {
            if (selectLength > 0)
            {
                originalValue = originalValue.Remove(selectStart, selectLength);
                return NextControlValue(originalValue, selectStart, 0, keyChar);
            }
            else
            {
                return originalValue.Insert(selectStart, keyChar);
            }
        }
        else
        {
            return originalValue + keyChar;
        }

    }

var previewValue = NextControlValue(textbox.Text, textbox.SelectionStart, textbox.SelectionLength, e.KeyChar + "");
查看更多
Evening l夕情丶
4楼-- · 2019-08-09 11:35

Use the TextBox.TextChanged event (inherited from Control).

Occurs when the Text property value changes.

My advice is to try not to hack this with the key events (down / press / up) - there are other ways to change a text-box's text, such as by pasting text from the right-click context menu. This doesn't involve pressing a key.

查看更多
Lonely孤独者°
6楼-- · 2019-08-09 11:45

The previous answers are incomplete with regards to the actual original question: how to retrieve the contents of the Text property when the user has just pressed a key (and including that keypress)?

The KeyUp event happens to be fired AFTER the contents of the Text property actually change, so using this particular order of events, you can retrieve the latest value of the text contents just using a KeyUp event handler.

The KeyPress event doesn't work because that gets fired BEFORE the change of the Text property.

查看更多
男人必须洒脱
7楼-- · 2019-08-09 11:47

You can try with KeyPress event:

int position = textBox1.SelectionStart;
string changedText = textBox1.Text.Insert(position, e.KeyChar.ToString());
查看更多
登录 后发表回答