Insert text at the beginning of a text box

孤人 提交于 2021-02-05 05:25:26

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!