且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从GridView,asp.net计算所选行的总和

更新时间:2023-02-10 13:12:40

研究此示例并根据您的需要进行调整:

aspx页面:

Study this example and adapt it to your need:
the aspx page:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default7.aspx.vb" Inherits="Default7" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                   <asp:Label ID="Label1" runat="server" Text="Checkbox"></asp:Label>
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="CheckBox1" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>

    </form>
</body>
</html>





背后的代码:



the code behind:

Imports System.Data

Partial Class Default7
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            Dim dt As New DataTable()
            dt.Columns.Add("Quantity")
            dt.Rows.Add("1")
            dt.Rows.Add("2")
            dt.Rows.Add("3")
            dt.Rows.Add("4")
            GridView1.DataSource = dt
            GridView1.DataBind()

        End If
    End Sub


    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim sum As Integer = 0
        For Each row As GridViewRow In GridView1.Rows
            Dim chkbox As CheckBox
            chkbox = CType(row.FindControl("CheckBox1"), CheckBox)
            If chkbox.Checked Then
                sum = sum + row.Cells(1).Text.ToString()
            End If
        Next
        TextBox1.Text = sum
    End Sub
End Class