-1

textbox複数の名前textbox1,textbox2,textbox3 などにアクセスしたいのですが、個別の名前ではなくループでアクセスしたいです。そのため、この var 名を作成する関数を 1 つ作成しました。

public string[] nameCre(string cntrlName, int size)
{
    string[] t = new string[size];

    for (int i = 0; i < size; i++)
    {
        t[i] = cntrlName.ToString() + (i + 1);
    }
    return t;
}

したがって、この関数はnameCre("Textbox",5);TextBox1、TextBox2 ... TextBox5 を正常に返します。

しかし、この文字列を TextBox コントロールに変換しようとすると

string[] t = new string[50];
t=  nameCre("TextBox",5);    
foreach (string s in t)
{
    ((TextBox) s).Text = "";
}

それは私にエラーを与えます:

タイプ 'string' を 'System.Windows.Forms.TextBox' に変換できません....

どうすればこの仕事を達成できますか?

4

4 に答える 4

0

おそらくこれが必要です-

        string[] t = new string[50];
        t = nameCre("TextBox", 5);

        foreach (string s in t)
        {
            if (!string.IsNullOrEmpty(s))
            {
                Control ctrl = this.Controls.Find(s, true).FirstOrDefault();
                if (ctrl != null && ctrl is TextBox)
                {
                    TextBox tb = ctrl as TextBox;
                    tb.Text = "";
                }
            }
        }
于 2012-07-12T03:58:24.910 に答える
0
string[] t= new string[50];
    t= nameCre("TextBox",5);

foreach (string s in t){
TextBox tb = (TextBox)this.Controls.FindControl(s);
tb.Text = "";
}

テキストボックスが多い場合

foreach (Control c in this.Controls)
{
  if (c.GetType().ToString() == "System.Windows.Form.Textbox")
  {
    c.Text = "";
  }
}
于 2012-07-12T02:58:31.573 に答える
0

この投稿はかなり古いですが、とにかく私はあなた(またはそのような問題を抱えている他の人)に答えを与えることができると思います:

TextBox の配列 (またはリスト) を使用することが、それを行うための最良の解決策になると思います。

        // using an Array:
        TextBox[] textBox = new TextBox[5];
        textBox[0] = new TextBox() { Location = new Point(), /* etc */};
        // or
        textBox[0] = TextBox0; // if you already have a TextBox named TextBox0

        // loop it:
        for (int i = 0; i < textBox.Length; i++)
        {
            textBox[i].Text = "";
        }

        // using a List:  (you need to reference System.Collections.Generic)
        List<TextBox> textBox = new List<TextBox>();
        textBox.Add(new TextBox() { Name = "", /* etc */});
        // or
        textBox.Add(TextBox0); // if you already have a TextBox named TextBox0

        // loop it:
        for (int i = 0; i < textBox.Count; i++)
        {
            textBox[i].Text = "";
        }

これが役立つことを願っています:)

于 2015-09-03T07:45:24.603 に答える
0
var t = nameCre("TextBox",5);

foreach (var s in t)
{
    var textBox = new TextBox {Name = s, Text = ""};
}
于 2012-07-12T03:10:47.740 に答える