-1

我已经编写了这段代码来将每个文本框值绑定到标签这适用于每个单个值但现在我希望标签绑定每个值的次数意味着我为此使用 for 循环,以便我可以绑定不同的值并显示它动态迭代次数,所以怎么可能。

protected void Button1_Click(object sender, EventArgs e)
{
    string name = TextBox1.Text;
    string order = TextBox2.Text;
    int qty = Convert.ToInt32(TextBox3.Text);
    int rate = Convert.ToInt32(TextBox4.Text);
    int discount = Convert.ToInt32(TextBox5.Text);
    int c = (Convert.ToInt32(TextBox3.Text) * Convert.ToInt32(TextBox4.Text) - Convert.ToInt32(TextBox5.Text));
    TextBox6.Text = c.ToString();
    int total = Convert.ToInt32(TextBox6.Text);
    string j="";
    for (int i = 1; i < 5; i++)
    {
        j += i + "";

        Label1.Text = j + "customer name is:-" + name;
        Label2.Text = j + "order item is:-" + order;
        Label3.Text = j + "quantity is:-" + qty;
        Label4.Text = j + "rate of the item is:-" + rate;
        Label5.Text = j + "discount given to the item is:-" + discount;
        Label6.Text = j + "Total of the item is:-" + total;
    }

    TextBox1.Text = string.Empty;
    TextBox2.Text = string.Empty;
    TextBox3.Text = string.Empty;
    TextBox4.Text = string.Empty;
    TextBox5.Text = string.Empty;
    TextBox6.Text = string.Empty;
}
4

1 回答 1

0

在你的循环中,你正在覆盖每个标签的值......所以最后你只剩下最终值。

您想要做的是将标签的值设置为其以前的 新值

Label1.Text += j + "customer name is:-" + name;

与以下+=内容相同:

Label1.Text = Label1.Text + j + "customer name is:-" + name;

为了可读性,您可能想要更多类似的东西:

for (int i = 1; i < 5; i++)
{   
    Label1.Text += i + " customer name is:-" + name + "<br />";
    Label2.Text += i + " order item is:-" + order + "<br />";
    Label3.Text += i + " quantity is:-" + qty + "<br />";
    Label4.Text += i + " rate of the item is:-" + rate + "<br />";
    Label5.Text += i + " discount given to the item is:-" + discount + "<br />";
    Label6.Text += i + " Total of the item is:-" + total + "<br />";
}

而且您需要对诸如Convert.ToInt32(TextBox3.Text). 如果转换失败, Convert.ToInt32会引发异常。

如果您进入大循环,您可能需要考虑类似StringBuilder的东西。

于 2013-03-29T04:00:57.097 回答