2017-05-10 5 views
0
Instead of writing below three lines how can I declare them in 1 line? 

    Label sub1 = (Label) GridView1.Rows[0].FindControl("Label5"); 
    Label sub2 = (Label) GridView1.Rows[1].FindControl("Label5"); 
    Label sub3 = (Label) GridView1.Rows[2].FindControl("Label5"); 

「0」または「1」0r「2」の代わりに「i」を入れると、「2」という値だけが表示されます。そのため、すべての方法を1行に書きたいのですか?ラベルを1行で宣言する方法は?

The code is: 

for (int i = 0; i < ds.Rows.Count; i++) { 
    Label price = (Label) GridView1.Rows[i].FindControl("Label5"); 
    TextBox ttlqnt = (TextBox) GridView1.Rows[i].FindControl("TextBox1"); 
    decimal y = decimal.Parse(ttlqnt.Text); 
    Label pricecal = (Label) GridView1.Rows[i].FindControl("Label2"); 
    decimal z = (y * decimal.Parse(price.Text)); 
    pricecal.Text = "Rs." + (z.ToString()); 
    Label sub1 = (Label) GridView1.Rows[0].FindControl("Label5"); 
    Label sub2 = (Label) GridView1.Rows[1].FindControl("Label5"); 
    Label sub3 = (Label) GridView1.Rows[2].FindControl("Label5"); 
    TextBox ttlqnt1 = (TextBox) GridView1.Rows[0].FindControl("TextBox1"); 
    TextBox ttlqnt2 = (TextBox) GridView1.Rows[1].FindControl("TextBox1"); 
    TextBox ttlqnt3 = (TextBox) GridView1.Rows[2].FindControl("TextBox1"); 
    decimal c1 = decimal.Parse(ttlqnt1.Text); 
    decimal c2 = decimal.Parse(ttlqnt2.Text); 
    decimal c3 = decimal.Parse(ttlqnt3.Text); 
    decimal y1 = c1 * decimal.Parse(sub1.Text); 
    decimal y2 = c2 * decimal.Parse(sub2.Text); 
    decimal y3 = c3 * decimal.Parse(sub3.Text); 
    decimal y4 = y1 + y2 + y3; 
    Subtotal.Text = y4.ToString(); 
} 
+1

私はなぜあなたが欲しいと思っていますか?もちろん、行数が動的でない限り、コードはループ内になくても読みやすくなります。 –

+0

行の値(0/1/2など)がないとエラーが表示されるため、修正したいと考えています。 – Swadesh

答えて

0

をやっているなぜあなたはそれらを個別に定義することはできません表示されていないけれども、これは何をしたいですか?

decimal zTotal = 0; 

for (int i = 0; i < ds.Rows.Count; i++) { 
    Label price = (Label) GridView1.Rows[i].FindControl("Label5"); 
    TextBox ttlqnt = (TextBox) GridView1.Rows[i].FindControl("TextBox1"); 
    decimal y = decimal.Parse(ttlqnt.Text); 
    Label pricecal = (Label) GridView1.Rows[i].FindControl("Label2"); 
    decimal z = (y * decimal.Parse(price.Text)); 
    pricecal.Text = "Rs." + (z.ToString()); 

    zTotal += z; 
} 

Subtotal.Text = zTotal.ToString(); 

すでにpriceでその値を持っているので、私はsub1sub2sub3を削除しました。 ハードコードされたコードではなく、ループ内のすべての値の合計を保持するzTotalを追加しましたy1 + y2 + y3

0

ループ内でその宣言を引き出す以外の方法はありません。私は同様にあなたがすでに

List<Label> labels = new List<Label>(); 

for(int i=0; i<4; i++) 
{ 
    labels.Add((Label)GridView1.Rows[i].FindControl("Label5")); 
} 
+0

これは別に宣言しても問題ありませんが、難しさはここではありません。ラベルsub1 =(ラベル)GridView1.Rows [0] .FindControl( "Label5"); ラベルsub2 =(ラベル)GridView1.Rows [1] .FindControl( "Label5"); ラベルsub3 =(ラベル)GridView1.Rows [2] .FindControl( "Label5"); – Swadesh

関連する問題