我在运行时创建了许多文本框然后我想向它们添加值.. 之后我添加一个按钮来单击它并计算文本框中的所有这些值但我不知道如何访问这些文本框? ?
谢谢
您是否尝试过 FindControl 方法?
private void Button1_Click(object sender, EventArgs MyEventArgs)
{
// Find control on page.
Control myControl1 = FindControl("TextBox2");
if(myControl1!=null)
{
// Get control's parent.
Control myControl2 = myControl1.Parent;
Response.Write("Parent of the text box is : " + myControl2.ID);
}
else
{
Response.Write("Control not found");
}
}
参考: http: //msdn.microsoft.com/en-us/library/system.web.ui.control.findcontrol (v=vs.71).aspx
我不时使用这种方法,只要您知道文本框的名称或您需要的任何控件。
FindControl("textboxnamehere").Text = "This would put this string in the current text box";
这只是一个示例,假设您将文本框放在堆栈面板中 - 您需要一个容器!,
private void Button_Click(object sender, RoutedEventArgs e)
{
var sum = 0.0;
foreach (var child in stackPanel.Children)
{
var textBox = child as TextBox;
if (textBox == null) continue;
double value;
Double.TryParse(textBox.Text, out value);
sum += value;
}
Console.WriteLine(sum);
}
当然,我假设您知道您可能想要验证输入(使用数字文本块) button.Click += Button_click; , ETC..
编辑问题
private void Button_Click(object sender, RoutedEventArgs e)
{
var sum = 0.0;
for (int i = 1; i < grid.Children.Count; i++ )
{
var textBox = grid.Children[i] as TextBox;
if (textBox == null) continue;
double value;
Double.TryParse(textBox.Text, out value);
sum += value;
}
Console.WriteLine(sum);
}
如果你有一个容器中的文本框,比如 StackPanel,你可以做这样的事情......
private void btnCalculate_Click(object sender, EventArgs e)
{
var total = 0;
var textboxes = StackPanelParent.Children.OfType<TextBox>();
foreach (var textbox in textboxes)
{
var input = 0;
int.TryParse(textbox.Text, out input);
total += input;
}
MessageBox.Show(total.ToString());
}