如何在一行中声明标签?

时间:2017-05-10 11:11:36

标签: c# asp.net

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

如果我把“i”代替“0”或“1”0r“2”,它只显示“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();
}

2 个答案:

答案 0 :(得分:0)

除了在循环中拉出该声明之外别无选择;虽然我不明白为什么你不能单独定义它们同样你已经在做

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

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

答案 1 :(得分: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();

我已移除sub1sub2sub3,因为您已在price中拥有该值。 我添加了一个zTotal,它将保留循环中所有值的总和,而不是硬编码的y1 + y2 + y3