c# change textbox name in code

纵然是瞬间 提交于 2021-02-08 08:23:25

问题


i was just wondering if something like this is possible:

for(int i = 0; i < 7; i++)
{
    textbox + i + .text = aString;
}

I want to change a piece of code to work on multiple textboxes, without having to type the whole code 6 times. does anyone know if this is possible and how? Thanks :3


回答1:


in C# you can find your control in your page aspx.

Example:

for (int i = 0; i < 10; i++)
 {

     TextBox textBox = this.Page.FindControl("textbox" + i.ToString()) as TextBox;
     if (textBox != null)
     {
        textBox.Text = "change Text";
     }
  }



回答2:


Well, just telling you that i'm newbie....

public void AddStringToTextbox(int i, string value)
{
 switch(i)
 {
 case: 0:
 break;

 case: 1:
 textbox1.text = value;
 break;

 case: 2:
 textbox2.text = value;
 break;

 case: 3:
 textbox3.text = value;
 break;

 //and more
 }
}

//how to use

for(int i = 0; i < 7; i++)
{
 AddStringToTextbox(i, aString);
}



回答3:


Try this one for Winforms, should be a bit safer.

      var textBoxes = this.Controls.OfType<TextBox>();

      for (int i = 0; i < 10; i++)
      {
        var textBox = textBoxes.FirstOrDefault<TextBox>(t => t.Name.Equals("textBox" + i.ToString()));
        if(textBox != null)
        {
          textBox.Text = i.ToString();
        }
      }



回答4:


Try putting your controls in an array or list and reference them from there. E.g.:

public class MyClass
{
    private List<TextBox> textboxes;

    public MyClass()
    {
        this.InitializeComponent();
        textboxes = new List<TextBox>(){ textbox1, textbox2, textbox3 };
    }

    private void UpdateTextBoxes(string aString)
    {
        for(var i = 0; i < textboxes.Count; i++)
        {
            textboxes[i].Text = aString;
        }
    }
}

Or, if it is a simple an update as your question suggests, try

textbox1.Text = 
textbox2.Text = 
textbox3.Text = 
textbox4.Text = 
textbox5.Text = 
textbox6.Text = 
textbox7.Text = 
    aString;



回答5:


May be this help you. Make a list of TextBox and use where ever you need.

        List<TextBox> textBoxs = new List<TextBox>();

        textBoxs.Add(textBox1);
        textBoxs.Add(textBox2);
        textBoxs.Add(textBox3);
        textBoxs.Add(textBox4);
        textBoxs.Add(textBox5);
        textBoxs.Add(textBox6);
        textBoxs.Add(textBox7);

        for (int i = 0; i < 7; i++)
        {
            textBoxs[i].Text = aString;
        }


来源:https://stackoverflow.com/questions/34659916/c-sharp-change-textbox-name-in-code

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