我需要检查无限量文本框的文本和各种属性。我虽然我可以用下面的方式使用{i}(所以它会通过tbEavelength1,tbEavelength2,tbEavelength3等检查)这样做但这不起作用,想知道是否有人有任何想法?
for (int i = 1; i <= comboBox1.SelectedIndex + 1; i++)
{
if (tbEaveLength{i}.IsEnabled == false)
{
eaveLength{i} = 0;
}
else if (tbEaveLength{i}.Text == "")
{
throw new Exception("EaveLength {i} must have a value");
}
else if (!double.TryParse(tbEaveLength{i}.Text, out eaveLength{i}))
{
throw new Exception("EaveLength {i} must be numerical");
}
}
提前感谢您的帮助!
答案 0 :(得分:1)
创建List<TextBox>
然后使用索引获取文本框并使用List<double>
执行相同的操作是什么?
//List<TextBox> listTextBoxes = new List<TextBox>();
//populate the list of textboxes
//List<double> listEaveLength = new List<double>();
for (int i = 1; i <= comboBox1.SelectedIndex + 1; i++)
{
if (listTextBoxes[i].IsEnabled == false)
{
listEaveLength[i] = 0;
}
else if (listTextBoxes[i].Text == "")
{
throw new Exception(listTextBoxes[i].Name + " must have a value");
}
else if (!double.TryParse(listTextBoxes[i].Text, out listEaveLength[i]))
{
throw new Exception(listTextBoxes[i].Name + " must be numerical");
}
}
如上所述 millimoose 管理并行数组可能很难而且不是更好的解决方案。 所以你可以创建一个这样的类:
class DataStructure
{
public TextBox Textbox
{
get;
set;
}
public double Lenght
{
get;
set;
}
public DataStructure(TextBox Textbox)
{
this.Textbox = Textbox;
}
}
然后始终使用List<DataStructure>
:
//List<DataStructure> myList = new LList<DataStructure>();
//myList.Add(new DataStructure(myTextBox));
//... populate your list
for (int i = 1; i <= comboBox1.SelectedIndex + 1; i++)
{
if (myList[i].Textbox.IsEnabled == false)
{
myList[i].Lenght = 0;
}
else if (myList[i].Textbox.Text == "")
{
throw new Exception(myList[i].Textbox.Name + " must have a value");
}
else if (!double.TryParse(myList[i].Textbox.Text, out myList[i].Lenght))
{
throw new Exception(myList[i].Textbox.Name + " must be numerical");
}
}
答案 1 :(得分:0)
您好,您可以尝试使用FindControl()方法查找文本框。我假设您正在使用Asp.net页面。
例如
for (int i = 1; i <= comboBox1.SelectedIndex + 1; i++)
{
var tbEaveLength = FindControl("tbEaveLength" + i);
if (tbEaveLength.IsEnabled == false)
{
eaveLength = 0;
}
else if (tbEaveLength.Text == "")
{
throw new Exception("EaveLength {i} must have a value");
}
else if (!double.TryParse(tbEaveLength{i}.Text, out eaveLength{i}))
{
throw new Exception("EaveLength {i} must be numerical");
}
}
答案 2 :(得分:0)
如果你在你的代码隐藏文件中,那么你可以使用方法FindName
通过传递其名称来获取文本框的实例,然后可以在这个特定的文本框上执行操作 -
for (int i = 1; i <= comboBox1.SelectedIndex + 1; i++)
{
TextBox textBox = (TextBox)FindName("tbEaveLength" + i);
if (textBox.IsEnabled == false)
{
eaveLength{i} = 0;
}
else if (textBox.Text == "")
{
throw new Exception("EaveLength {i} must have a value");
}
else if (!double.TryParse(textBox.Text, out eaveLength{i}))
{
throw new Exception("EaveLength {i} must be numerical");
}
}