-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 に答える