【问题标题】:Looping Through Gridview with IF ELSE statement使用 IF ELSE 语句循环遍历 Gridview
【发布时间】:2015-07-10 14:09:46
【问题描述】:

我正在尝试向 GridView 添加条件语句;但是,它似乎只在第一行工作。

我有一个 HiddenField,我在其中提取我的折扣值,然后是一个标签 在我返回所述值的地方,只有当该值不是 0.00 时,它才会产生中断。 我假设我可以简单地遍历网格行来完成这个;但是,如前所述,它仅适用于第一行。这是我的代码:

    // Number of rows in grid
            int rowsCount = grid.Rows.Count;
            //Loop through the rows
            for (int i = 0; i < rowsCount; i++)
            {
                Label discountLabel = (Label)(grid.Rows[0].FindControl("discountLabel"));
                HiddenField discount = (HiddenField)(grid.Rows[0].FindControl("HiddenField1"));
                string discountValue = discount.Value;
                if (discountValue == "0.00")
                {
                    discountLabel.Text = "<br />";
                }
                else
                {
                    discountLabel.Text = "NOW&nbsp;" + (String.Format("{0:c}", discountValue));
                }
            }

【问题讨论】:

  • 将 grid.Rows[0] 更改为 grid.Rows[i]

标签: c# asp.net gridview


【解决方案1】:

grid.Rows[0] 返回网格中的第一行,您要循环所有行。所以改用循环变量i

for (int i = 0; i < rowsCount; i++)
{
    Label discountLabel = (Label)(grid.Rows[i].FindControl("discountLabel"));
    HiddenField discount = (HiddenField)(grid.Rows[i].FindControl("HiddenField1"));
    string discountValue = discount.Value;
    if (discountValue == "0.00")
    {
        discountLabel.Text = "<br />";
    }
    else
    {
        discountLabel.Text = "NOW&nbsp;" + (String.Format("{0:c}", discountValue));
    }
}

【讨论】:

  • 哦,天哪,要么我是盲人,要么我今天没有喝足够的咖啡!谢谢你。我会在 10 分钟内标记为正确答案。
  • @Faron:顺便说一句,如果discountValue 是字符串,则不能使用String.Format("{0:c}", discountValue)。然后你不会得到货币格式,因为它只适用于像 decimaldouble 这样的数字类型。因此首先解析它:decimal discount = decimal.Parse(discountValue)。现在你可以使用String.Format("{0:c}", discount)
猜你喜欢
  • 2017-07-24
  • 2020-05-02
  • 1970-01-01
  • 1970-01-01
  • 2015-10-28
  • 2017-02-17
  • 2015-11-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多