Variable declarations following if statements

后端 未结 4 581
甜味超标
甜味超标 2020-11-28 11:29

An issue came up on another forum and I knew how to fix it, but it revealed a feature of the compiler peculiar to me. The person was getting the error \"Embedded statement c

4条回答
  •  迷失自我
    2020-11-28 12:01

    Adding the closing and opening braces on the else part of the if helped me like i have done below as opposed to what i was doing before adding them;

    Before: this caused the error:

    protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "ADD")
            {
    
                CATEGORY cat = new CATEGORY
                {
    
                    NAME = tbxCategory.Text.Trim(),
                    TOTALSALEVALUE = tbxSaleValue.Text.Trim(),
                    PROFIT = tbxProfit.Text.Trim()
    
                };
                dm.AddCategory(cat, tbxCategory.Text.Trim());
            }
            else
            // missing brackets - this was causing the error
                var c = getCategory();
                c.NAME = tbxCategory.Text.Trim();
                c.TOTALSALEVALUE = tbxSaleValue.Text.Trim();
                c.PROFIT = tbxProfit.Text.Trim();
                dm.UpdateCategory(c);
    
            btnSearchCat_Click(btnSearchCat, e);
        }
    

    After: Added brackets in the else branch

    protected void btnAdd_Click(object sender, EventArgs e)
        {
            if (btnAdd.Text == "ADD")
            {
    
                CATEGORY cat = new CATEGORY
                {
    
                    NAME = tbxCategory.Text.Trim(),
                    TOTALSALEVALUE = tbxSaleValue.Text.Trim(),
                    PROFIT = tbxProfit.Text.Trim()
    
                };
                dm.AddCategory(cat, tbxCategory.Text.Trim());
            }
            else
            {
                var c = getCategory();
                c.NAME = tbxCategory.Text.Trim();
                c.TOTALSALEVALUE = tbxSaleValue.Text.Trim();
                c.PROFIT = tbxProfit.Text.Trim();
                dm.UpdateCategory(c);
            }
            btnSearchCat_Click(btnSearchCat, e);
        }
    

提交回复
热议问题