开发者

C# for loop on button1_click1, int i seems to be advancing wrong

Trying to get it so that if you left click, it will fill in 4 text boxes, then if you use the dropdownlists and click on it again, it will fill in 4 different text boxes - have to get it to fill a total of 20, 4 at a time.

 开发者_高级运维   int carpick, qty, total, i;

    protected void Button1_Click1(object sender, EventArgs e)
    {
        for (i = 0; i != 5; ++i)
        {
            carpick = 0; qty = 0; total = 0;
            {

                carpick = Convert.ToInt32(CarpickDD.SelectedItem.Value);
                qty = Convert.ToInt32(QTYDD.SelectedItem.Value);
                total = ((carpick * qty) + (750 * qty));

                Label1.Text = CarpickDD.SelectedItem.Text;
                Label2.Text = CarpickDD.SelectedItem.Value;
                Label3.Text = QTYDD.SelectedItem.Value;
                Label4.Text = Convert.ToString(total);}

        if (i != 1)
        {

            carpick = Convert.ToInt32(CarpickDD.SelectedItem.Value);
            qty = Convert.ToInt32(QTYDD.SelectedItem.Value);
            total = ((carpick * qty) + (750 * qty));
            Label5.Text = CarpickDD.SelectedItem.Text;
            Label6.Text = CarpickDD.SelectedItem.Value;
            Label7.Text = QTYDD.SelectedItem.Value;
            Label8.Text = Convert.ToString(total);
       }

        }
    }

enter code here


Every time you click on the button, your for loop starts at i = 0. Therefore, you are not maintaining any state from each invocation to the next; your button doesn’t “remember” how often you have clicked it before.

That said, you are also not making any use of the variable i inside the loop (except for the if (i != 1)). In other words, your loop currently does the same thing on every button click, and it does the same thing five times for each click. If you want to fill in different text boxes the second time you click on the button, surely it should do something different the second time round?


I think you want this:

int carpick, qty, total, i = 0;

protected void Button1_Click1(object sender, EventArgs e)
{
    carpick = Convert.ToInt32(CarpickDD.SelectedItem.Value);
    qty = Convert.ToInt32(QTYDD.SelectedItem.Value);
    total = ((carpick * qty) + (750 * qty));

    switch (i++)
    {
        case 0:
            Label1.Text = CarpickDD.SelectedItem.Text;
            Label2.Text = CarpickDD.SelectedItem.Value;
            Label3.Text = QTYDD.SelectedItem.Value;
            Label4.Text = Convert.ToString(total);
            break;

        case 1:
            Label5.Text = CarpickDD.SelectedItem.Text;
            Label6.Text = CarpickDD.SelectedItem.Value;
            Label7.Text = QTYDD.SelectedItem.Value;
            Label8.Text = Convert.ToString(total);
            break;

        case 2:
            ..... etc ....
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜