简体   繁体   中英

textbox Insert and remove function in vb.net or c#

How to update the text from the TextBox control?

Consider a TextBox that already contains the string "Wel"

To insert text in the TextBox , I use:

   TextBox1.Text = TextBox1.Text.Insert(3, "come")

And to remove characters from the TextBox :

    TextBox1.Text = TextBox1.Text.Remove(3, 4)

But I need to be able to do this:

    TextBox1.Text.Insert(3, "come");
    TextBox1.Text.Remove(3, 4);

However, this code doesn't update the TextBox .

It this possible?

Can this be accomplished via the append method?

Text property of TextBox is of type string which is immutable it's not possible to change the existing string. Insert() or Remove() returns a new instance of string with the modification and you will have to assign this new instance back to TextBox's Text property.

There is TextBox.AppendText() that you might be interested in. It appends text to the end of the string but you cannot do anything like Insert() or Remove() with it though.

EDIT:

for your keypress, you could do something like this

        char charToReplace = (char) (e.KeyChar + 1);    // substitute replacement char
        textBox1.SelectedText = new string(charToReplace,1);
        e.Handled = true;

'string' is a immutable type, so each time string value changes new memory is allocated. So if you want to insert or remove text from TextBox , you have to assign it back to TextBox.Text property. However, if you just want to append text to the TextBox.Text , you can do

textBox.AppendText("Hello");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM