Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert text at the beginning of a text box

Tags:

c#

insert

textbox

I need to insert some text as the first character of my textbox when a button is clicked.

Here is what I have tried:

private void btnInsert_Click(object sender, EventArgs e)
{
    txtMainView.Text.Insert(0, "TEST");
}

This fails to insert the text when I click the button. Anyone have an idea what I am doing wrong?

like image 644
Nathan Avatar asked Dec 27 '22 20:12

Nathan


2 Answers

Update for c# 6+

txtMainView.Text = $"TEST{txtMainView.Text}";

Original

You can also go with

txtMainView.Text = "TEST" + txtMainView.Text; 

as an alternative.

like image 32
Yatrix Avatar answered Jan 12 '23 00:01

Yatrix


txtMainView.Text = txtMainView.Text.Insert(0, "TEST");

Strings are immutable in .NET Framework so each operation creates a new instance, obviously does not change original string itself!

For more details on String class see MSDN page Strings (C# Programming Guide)

like image 117
sll Avatar answered Jan 11 '23 23:01

sll