2017-05-10 1 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"값만 표시됩니다. 그래서 모든 방법을 한 줄로 작성하는 것이 좋습니까?레이블을 한 줄로 선언하는 방법은 무엇입니까?

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

이것이 무엇입니까? 이미 price에서 그 값을 가지고 있기 때문에

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(); 

나는 sub1, sub2, sub3를 제거했습니다. 을 추가하여 루프의 모든 값을 하드 코드 된 값으로 유지합니다. 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

관련 문제