getting sum of text from all the dynamically generated control

前端 未结 3 1785
小蘑菇
小蘑菇 2021-01-26 02:10

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. Y

相关标签:
3条回答
  • 2021-01-26 02:55

    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
    
    0 讨论(0)
  • 2021-01-26 03:02
     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));
                }
                );
    
    0 讨论(0)
  • 2021-01-26 03:02
    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(); 
    
    0 讨论(0)
提交回复
热议问题