-1

我想添加所有动态生成的用户控件的价格(标签)并设置为 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();
    }
4

1 回答 1

0

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

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();
}
于 2017-12-02T09:17:59.270 回答