我在按钮上单击面板内部和存储编号创建动态文本框 并且想要检索它的文本并总计那个数字我该怎么做?
以下是我生成文本框的代码
private void btnMaterialAdd_Click(object sender, EventArgs e)
{
TextBox[] txtTeamNames = new TextBox[100];
txtTeamNames[i] = new TextBox();
string name = "TeamNumber" + i.ToString();
txtTeamNames[i].Location = new Point(1, i * 30 );
txtTeamNames[i].Width = 30;
txtTeamNames[i].Name = "ID" + i;
txtTeamNames[i].Visible = true;
int num = i + 1 ;
txtTeamNames[i].Text = num.ToString();
panel1.Controls.Add(txtTeamNames[i]);
}
如何计算每个文本框的总值并显示?
答案 0 :(得分:1)
摆脱数组并使用类级别的列表(不是方法中的局部变量):
private List<TextBox> TextBoxes = new List<TextBox>();
private void btnMaterialAdd_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
int i = TextBoxes.Count + 1;
tb.Location = new Point(1, i * 30);
tb.Width = 30;
tb.Name = "ID" + i;
tb.Text = i.ToString();
TextBoxes.Add(tb);
panel1.Controls.Add(tb);
}
现在你可以迭代那个列表来获得总数:
private void btnTotal_Click(object sender, EventArgs e)
{
int value;
int total = 0;
foreach (TextBox tb in TextBoxes)
{
if (int.TryParse(tb.Text, out value))
{
total = total + value;
}
else
{
MessageBox.Show(tb.Name + " = " + tb.Text, "Invalid Value");
}
}
MessageBox.Show("total = " + total.ToString());
}