问题
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?
回答1:
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)
回答2:
Update for c# 6+
txtMainView.Text = $"TEST{txtMainView.Text}";
Original
You can also go with
txtMainView.Text = "TEST" + txtMainView.Text;
as an alternative.
来源:https://stackoverflow.com/questions/11748451/insert-text-at-the-beginning-of-a-text-box