I Create dynamic text box on button click inside panel and store number and want to retrieve its text and make total of that number how can i do that?
Following is my code for text box generation
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]);
}
How to count total value of each text box and display?
Get rid of the Array and use a List at Class Level (not a local variable in your method):
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);
}
Now you can iterate over that List when to get a total:
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());
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.