2011-02-23 35 views
1

我需要获得列表视图中列中所有项目的总和。我在itemdatabound事件中加入了下面的代码,但是在测试之后才意识到它只会得到绑定的东西,oops。在ListView中获取列的总数

所以我一直在寻找一些帮助,将其转换为显示我的列中所有项绑定到ListView的总数。

谢谢。

if (e.Item.ItemType == ListViewItemType.DataItem)  
     { 
      ListViewDataItem item = (ListViewDataItem)e.Item;   

      Label lblQty = (Label)e.Item.FindControl("lblQuantity"); 
      if (lblQty == null) 
      { 
       return; 
      } 

      if (lblQty.Text.Length == 0 || lblQty.Text == "") 
      { 
       return; 
      } 
      else 
      { 
       ListViewTotal += int.Parse(lblQty.Text); 
      } 
     } 
+0

如果你想要的东西以外的东西是什么绑定。你将有查询数据源。 – Magnus 2011-02-23 21:00:18

回答

1

我发现要做到这一点的最好方法是为您绑定的控件实现OnDataBinding方法。例如:

<asp:ListView ID="ListView1" runat="server"> 
    <ItemTemplate> 
     <asp:Literal ID="yourLiteral" runat="server" 
      OnDataBinding="yourLiteral_DataBinding"></asp:Literal> 
    </ItemTemplate> 
</asp:ListView> 

首先定义一个全局计数器在您的.cs:

private int _quantityTotal = 0; 

然后实现OnDataBinding的控制:

protected void yourLiteral_DataBinding(object sender, System.EventArgs e) 
{ 
    // You could get anything here to get a value including calling a DB 
    // call if you want for each item that is being bound. 
    Literal lt = (Literal)(sender); 
    int quantity = (int)(Eval("yourQuantityField")); 
    _quantityTotal += quantity; 
    lt.Text = quantity.ToString(); 
} 

现在你已经存储在_quantityTotal总您可以在发生数据绑定之后将其添加到页脚或其他内容中,例如OnDataBound事件。

+0

感谢Kelsey,真的很喜欢这种方法。 – PixelMuse 2011-02-25 15:32:10

0

是的,你必须查询数据库获取此值,或者根据您有约束力的东西,通过你要绑定的收集循环,并从类或数据集/数据表你要绑定的值相加到它。

HTH。