0
votes

i have a windows form in which there are controls listed below panel1 button1 = add new mobiles button2 = ok When clicking on button1 an usercontrol is added. You can add as much userControls as you wish. The userControl defines consists of five controls:

combobox1 combobox2 textbox1 textbox2 textbox3

i want to add the text of textbox3 of all the dynamically generated usercontrol control and set to a label on the winform how can i do that? by clicking the ok button i have tried this code

foreach (Control ctrl in panel1.Controls)
{
      if (ctrl is UserControl)
      {
           UserControl1 myCrl = ctrl as UserControl1;
           int g;
           // but this doesnt happen an error is coming
           g += Convert.ToInt32(myCrl.textbox3.Text);  
      }
}

how to get sum of all the dynamically generated control's text

3
What is the error message? And "int g" should be given a value (most likely 0, ie. int g = 0;).Inisheer
Please show us the error message. I would assume you are trying to convert a non-numeric value to integer! Furthermore you should define g outside the foreachPilgerstorfer Franz

3 Answers

1
votes

Probably your "error" is that you're declaring g inside of the foreach loop, so you don't actually make any sum. Furthermore, you don't initialize it. Change your code to:

var g = 0;
foreach (Control ctrl in Controls)
{
    if (ctrl is UserControl1)
    {
        var myCrl = ctrl as UserControl1;
        g += Convert.ToInt32(myCrl.textbox2.Text);
    }
}
//Set your label's text
2
votes
 int sum = 0;
        panel1.Controls.OfType<UserControl>().ToList().ForEach(
            x =>
            {
                TextBox ctl = x.Controls.OfType<TextBox>().Where(y => y.Name == "textbox2").FirstOrDefault();
                sum += (ctl == null ? 0 : (!String.IsNullOrEmpty(ctl.Text.Trim()) ? Convert.ToInt32(ctl.Text.Trim()) : 0));
            }
            );
1
votes
double totalSumValue = 0;
foreach (Control ctrl in Controls)
{
    if (ctrl is UserControl)
    {
        var myCrl = ctrl as UserControl;
        totalSumValue  += Convert.ToInt32(myCrl.textbox3.Text);
    }
}
lblSumValue.text=totalSumValue.toString();