Getting sum of textbox from all the dynamically generated usercontrols

80 views Asked by At

I want to add the price(label) of all the dynamically generated usercontrol and set to a label on the winform how can i do that? by clicking the ok button on the winform i tried this code but it didn't add the labels and the output is always 0 Here is the image : https://i.stack.imgur.com/2DpSh.jpg and this is my code :

 private void add_Click(object sender, EventArgs e)
    {
        double g = 0;
        foreach (Control ctrl in Controls)
        {
            if (ctrl is DynaItems)
            {
                var myCrl = ctrl as DynaItems;
                g += Convert.ToInt32(myCrl.price.Text);
            }
        }
        textBox1.Text = g.ToString();
    }
1

There are 1 answers

0
Haytam On BEST ANSWER

I think this might be coming from the fact that you want a double while you're converting to an Int32. Try this code and at the same time check if your price control has its property Text correct.

private void add_Click(object sender, EventArgs e)
{
    double g = 0;

    // Controls.OfType will automatically find your DynaItems controls and cast them for you
    foreach (DynaItems dynaItem in Controls.OfType<DynaItems>())
    {
        // Breakpoint here and check the value of dynaItem.price.Text
        g += double.Parse(dynaItem.price.Text);
    }

    textBox1.Text = g.ToString();
}