0

我想在 GridView 页脚的标签上显示名为“total”的列中的值。

“总计”列的值在每一行都是相同的,因此只要我们在该列中,选择哪个单元格都没有关系。

我正在为我的列“总计”使用模板字段,并通过使其可见性 = false 来隐藏它。所以我想要的是我想将名为 total 的列中的值显示到我的 gridview 内的标签上

这是我尝试过的代码示例,但它给出了一个错误:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
int total;
        if (e.Row.RowType == DataControlRowType.DataRow) 
        { 
            total = Convert.ToInt32(((DataRowView)e.Row.DataItem)["total"].ToString()); 
        } 
        if (e.Row.RowType == DataControlRowType.Footer) 
        { 
            Label lblamount7 = (Label)e.Row.FindControl("Label27"); 
            lblamount7.Text =total.ToString(); // use of unassigned local variable 'total'
        }
    }

这是隐藏列的aspx '> '>

4

2 回答 2

1

要隐藏列,请在 GridView 的模板字段中使用 Hiddeneeild。语法就像

<asp:TemplateField>
<ItemTemplate>
 <asp:HiddenField ID="HiddenField1" runat="server" Value='<%#Eval("Total") %>'/>


                        </ItemTemplate>
                        </asp:TemplateField> 

现在要计算总数并将其显示在 GridView 的页脚中,您可以这样做

int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType==DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Total"));
}
if(e.Row.RowType==DataControlRowType.Footer)
{
Label lblamount7 = (Label)e.Row.FindControl("lblTotal");
lblamount7.Text = total.ToString();
}
}

它肯定会奏效。祝你好运,如果有效,请发表评论。

于 2013-01-18T04:59:05.570 回答
0

它认为您需要在 DataRowView 演员周围加上括号—— DataItem["total"] 不存在:

改变这个:

total = Convert.ToInt32((DataRowView)e.Row.DataItem["total"].ToString());

total = Convert.ToInt32(((DataRowView)e.Row.DataItem)["total"].ToString());

--编辑

您需要在 RowDataBound 过程之外定义总计并将其初始化为 0。另外,请注意“+=”的使用——我假设您希望每个列的运行总计。如果没有,请将其更改回“=”,这将获取数据行中的最后一个总数。

private int total = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{

    if (e.Row.RowType == DataControlRowType.DataRow) 
    { 
        total += Convert.ToInt32(((DataRowView)e.Row.DataItem)["total"].ToString()); 
    } 
    if (e.Row.RowType == DataControlRowType.Footer) 
    { 
        Label lblamount7 = (Label)e.Row.FindControl("Label27"); 
        lblamount7.Text =total.ToString(); 
    }
}

祝你好运。

于 2013-01-18T04:49:58.303 回答