假设我有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.controlsi调用对象,但这并不完全是我想要的。我所做的是在运行时在窗体中添加了许多标签和文本框。我需要遍历表单才能获取所有内容。我把它写成一个带有很多if的for each,但我很好奇是否有一种动态的方式来实现它。
我已经在网上找了大约1-1:30个小时,但没有找到任何接近,感谢所有人的帮助。
发布于 2011-04-06 01:10:07
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);
}发布于 2011-04-06 01:01:58
您要使用的是FindControl方法。
VB中的示例:
Dim txtMileage As TextBox = CType(cphLeft.FindControl("txtMileage" & iControlCountDays.ToString()), TextBox)发布于 2011-04-06 01:40:18
也许这能解决你想要的东西:
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);
}https://stackoverflow.com/questions/5555553
复制相似问题