我有一个List对象,它自动填充了文本框的名称。现在,我想循环浏览所有这些文本框。 我怎样才能让C#知道List中的字符串名称实际上是具有该字符串名称的TextBox对象?
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
if (txtName.Text != "")
{
// do stuff
}
}
当前代码将txtName作为字符串读取。我希望它作为TextBox读取。
编辑 - 以下代码包含了我的解决方案。
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
TextBox textBox = this.Controls.Find(txtName, true).FirstOrDefault() as TextBox;
if (textBox.Text != "")
{
MessageBox.Show("Thanks Amir Popovich");
}
}
答案 0 :(得分:1)
使用Control.ControlCollection.Find
:
string textBoxName = "txtOpp1";
TextBox textBox = this.Controls.Find(textBoxName, true).FirstOrDefault() as TextBox;
在你的情况下:
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
var control = this.Controls.Find(txtName, true).FirstOrDefault();
if(control != null && control is TextBox)
{
TextBox textBox = control as TextBox;
if(textBox.Text != string.Empty)
{
//logic
}
}
}
答案 1 :(得分:1)
试试这个:
List<string> txtOppsNames = new List<string>();
for (int i = 1; i < numOpps; i++)
{
txtOppsNames.Add("txtOpp" + i);
}
foreach (var txtName in txtOppsNames)
{
var cntrl= FindControl(txtName);
if (cntrl!=null && cntrl is TextBox)
// do something with
((TextBox)cntrl)
}
答案 2 :(得分:0)