[ASP.NET]取得GridView本頁某欄位加總的值
前言
前陣子同事問我說要如何取得GridView本頁某欄位加總的值?
如下,計算畫面上「EmailPromotion」欄位的加總。
前置作業
先建立一些擴充方法提供之後的操作,如下,
{ public static Control FindControlRecurive(this Control parent, string controlId) { Control result = parent.FindControl(controlId); if (result == null && parent.HasControls()) { foreach (Control ctrl in parent.Controls) { result = ctrl.FindControlRecurive(controlId); } } return result; } public static int TryParseInt(this string value) { int result = 0; int.TryParse(value, out result); return result; } public static bool IsNull(this object value) { return (value == null); } }
aspx GridView的內容:
AllowPaging="True" AllowSorting="True" DataKeyNames="BusinessEntityID,FirstName" OnRowCommand="GridView1_RowCommand" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" DataSourceID="odsGridView"> <Columns> .......前5個欄位省略....... <asp:BoundField DataField="EmailPromotion" HeaderText="EmailPromotion" SortExpression="EmailPromotion" /> <asp:TemplateField HeaderText="EmailPromotion Template" SortExpression="EmailPromotion"> <ItemTemplate> <asp:TextBox runat="server" Text='<%# Eval("EmailPromotion") %>' ID="txtEmailPromotion"></asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> <PagerSettings Mode="NumericFirstLast" /> </asp:GridView>
解決方法
做法一:直接取得Cell的Text屬性來加總。
int EmailPromotionRowIndex = 5; foreach (GridViewRow r in GridView1.Rows) { result += r.Cells[EmailPromotionRowIndex].Text.TryParseInt(); } Response.Write(string.Format("Total EmailPromotiton:{0}", result.ToString()));
做法二:建立範本欄位,在範本欄位中加入控制項,然後透過FindControl找到該控制項,再取得該控制項的Text屬性來加總。
string EmailPromotionTextBoxId = "txtEmailPromotion"; foreach (GridViewRow r in GridView1.Rows) { Control txt = r.FindControlRecurive(EmailPromotionTextBoxId); result += txt.IsNull() ? 0 : (txt as TextBox).Text.TryParseInt(); } Response.Write(string.Format("Total EmailPromotiton:{0}", result.ToString()));
結論
如果有些GridView有勾選的話,可以在for迴圈中去filter。
Hi,
亂馬客Blog已移到了 「亂馬客 : Re:從零開始的軟體開發生活」
請大家繼續支持 ^_^