动态调用控件

时间:2011-04-05 16:59:43

标签: c# winforms

假设我有30个控件,所有lbls,都称为“lblA”,后面带有一个数字。

我也有30个文本框,同样的东西 - 后面带有一个数字称为“txtB”。

我究竟如何形成这一点。

for (i = 1; i < this.controls.count;i++)
{
    if ("lblA"+i=null)
    {
        break;
    }
    string A = string A + ("lblA" + i).Text
    string B = string B + ("txtB" + i).Text
}

我尝试了一些不同的东西,比如使用this.controls [i]调用对象,但这并不是我想要的。我正在做的是我在运行时添加的表单中有很多标签和文本框。我需要循环遍历表单以获取所有内容。我正在为每个人写一个有很多ifs的东西,但我很好奇是否有一种动态的方式来做它。

我在网上找了大约1-1:30小时,没有找到任何附近的内容,谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

var labels = new Dictionary<int, string>();
for (i = 1; i < this.controls.count;i++)
{
    var label = FindControl("lblA" + i) as Label;
    if (label == null)
    {
        break;
    }
    labels.Add(i, label.Text);
}

答案 1 :(得分:0)

您想要使用的是FindControl方法。

VB中的示例:

 Dim txtMileage As TextBox = CType(cphLeft.FindControl("txtMileage" & iControlCountDays.ToString()), TextBox)

答案 2 :(得分:0)

也许这会解决你所追求的目标:

void GetSpecialControls() {
  const string TXT_B = "txtB";
  const string LBL_A = "lblA";
  List<TextBox> textBoxList = new List<TextBox>();
  List<Label> labelList = new List<Label>();
  foreach (Control ctrl in this.Controls) {
    Label lbl = ctrl as Label;
    if (lbl != null) {
      if (lbl.Text.IndexOf(LBL_A) == 0) {
        labelList.Add(lbl);
      }
    } else {
      TextBox txt = ctrl as TextBox;
      if (txt != null) {
        if (txt.Text.IndexOf(TXT_B) == 0) {
          textBoxList.Add(txt);
        }
      }
    }
  }
  Console.WriteLine("Found {0} TextBox Controls.", textBoxList.Count);
  Console.WriteLine("Found {0} Label Controls.", labelList.Count);
}