从所有动态生成的用户控件中获取文本框的总和

Getting sum of textbox from all the dynamically generated usercontrols

我想添加所有动态生成的用户控件的价格(标签)并设置为 winform 上的标签,我该怎么做?通过单击 winform 上的确定按钮 我试过这段代码,但它没有添加标签,输出始终为 0 这是图片:https://imgur.com/a/ViPGt 这是我的代码:

 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();
    }

我认为这可能是因为您在转换为 Int32 时需要双精度数。试试这个代码,同时检查你的价格控制是否有 属性 文本正确。

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();
}