计算gridview中选中的复选框

Posted

技术标签:

【中文标题】计算gridview中选中的复选框【英文标题】:Count the checked checkboxes in gridview 【发布时间】:2012-10-26 14:29:47 【问题描述】:

我需要计算网格视图中选中的复选框,但我不知道该怎么做。也许我可以使用 javascript 并将计数保存在不显示样式的文本框中。我该怎么做?

【问题讨论】:

你需要在服务器端还是在客户端做这个? 【参考方案1】:

我写了客户端和服务器端的方法,看看它们并选择最适合你的!

请注意,我已将 jQuery 用于客户端逻辑,因为它是在客户端上操作 DOM 的更现代的方式

来源:

%>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
    <script type="text/javascript">
        function GetMarriedEmployees() 
        var counter = 0;
        $("#<%=gvEmployees.ClientID%> input[id*='chkIsMarried']:checkbox").each(function (index) 
            if ($(this).is(':checked'))
                counter++;
        );
        alert(counter);
        
    </script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:GridView ID="gvEmployees" AutoGenerateColumns="false" runat="server">
        <Columns>
            <asp:BoundField DataField="EmployeeId" />
            <asp:BoundField DataField="EmployeeName" />
            <asp:TemplateField>
                <ItemTemplate>
                    <asp:CheckBox ID="chkIsMarried" runat="server" Checked='<%# Bind("IsMarried") %>' />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <asp:Button ID="btnGetMarried" runat="server" Text="Server" OnClick="btnGetMarried_Click" /><br />
    <input type="button" value="Client" onclick="GetMarriedEmployees()" />
</asp:Content>

背后的代码:

namespace WebApplication1

    public partial class _Default : System.Web.UI.Page
    
        protected void Page_Load(object sender, EventArgs e)
        
            if (!Page.IsPostBack)
            
                List<Employees> employees = new List<Employees>()
            
                new EmployeesEmployeeId=1, EmployeeName="Bob", IsMarried=true,
                new EmployeesEmployeeId=2, EmployeeName="John", IsMarried=true
            ;

                gvEmployees.DataSource = employees;
                gvEmployees.DataBind();
            
        

        protected void btnGetMarried_Click(object sender, EventArgs e)
        
        int marriedEmployees = 0;
        foreach (GridViewRow row in gvEmployees.Rows)
        
            var isMarried = (CheckBox)row.FindControl("chkIsMarried");
            if(isMarried.Checked)
                marriedEmployees++;
         

        Response.Write(String.Format("Number of married employees = 0",marriedEmployees.ToString()));
    

    public class Employees
    
        public int EmployeeId  get; set; 
        public string EmployeeName  get; set; 
        public bool IsMarried  get; set; 
    

编辑:

我怀疑你可能是 VB.NET 开发人员所以这里是服务器端代码的 VB 版本:

Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then

            Dim employees As New List(Of Employees)

            Dim employee1 As Employees = New Employees()
            employee1.EmployeeId = 1
            employee1.EmployeeName = "Bob"
            employee1.IsMarried = False

            Dim employee2 As Employees = New Employees()
            employee2.EmployeeId = 2
            employee2.EmployeeName = "John"
            employee2.IsMarried = True

            employees.Add(employee1)
            employees.Add(employee2)

            gvEmployees.DataSource = employees
            gvEmployees.DataBind()

        End If
    End Sub

    Protected Sub btnGetMarried_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetMarried.Click
        Dim marriedEmployees As Integer = 0
        For Each row As GridViewRow In gvEmployees.Rows

            Dim isMarried As CheckBox = row.FindControl("chkIsMarried")
            If isMarried.Checked Then
                marriedEmployees += 1
            End If
        Next

        Response.Write(String.Format("Number of married employees = 0", marriedEmployees))

    End Sub
End Class

Public Class Employees
    Public Property EmployeeId As Integer
    Public Property EmployeeName As String
    Public Property IsMarried As Boolean
End Class

【讨论】:

【参考方案2】:

JavaScript 解决方案:

function CheckBoxCount() 
    var gv = document.getElementById("<%= Gridview1.ClientID %>");
    var inputList = gv.getElementsByTagName("input");
    var numChecked = 0;

    for (var i = 0; i < inputList.length; i++) 
        if (inputList[i].type == "checkbox" && inputList[i].checked) 
            numChecked = numChecked + 1;
        
    
    alert(numChecked);

标记

       <asp:GridView AllowSorting="true" ID="Gridview1" Width="98%" AutoGenerateColumns="False" runat="server">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <asp:CheckBox ID="cb_count" runat="server" onclick="CheckBoxCount();"></asp:CheckBox>
                    </ItemTemplate>
                </asp:TemplateField>
                ...
            </Columns>
        </asp:GridView>

【讨论】:

【参考方案3】:
Dim cnt as Integer = 0
For i=0 to GridView1.Rows.Count -1
   Dim chk as CheckBox = TryCast( GridView1.Row(i).Controls.Find("nameOfCheckBoxControlColum"),CheckBox)
if chk.Checked=True Then cnt += 1
Next

'Now cnt holds the number of Checked Boxes.

【讨论】:

【参考方案4】:
var count = $('input[name="numbChecked"]:checked').length;

这是获得计数的最简单方法,无需任何麻烦和额外解释! :)

【讨论】:

你真的应该在回答的同时附上每个部分的解释。【参考方案5】:

这对你有帮助

function Calculation()

    var grid = document.getElementById("<%=grdSelectFees.ClientID%>"); //grdSelectFees GridViewId
    for (var i = 0; i < grid.rows.length - 1 ; i++) 
    
        var CheckBox1 = $("input[id*=chkRow]")//chkRow Id of Check box
        if (CheckBox1[i].type == "checkbox" && CheckBox1[i].checked)
        
            //Code For If check Box Is Checked
        
    

【讨论】:

以上是关于计算gridview中选中的复选框的主要内容,如果未能解决你的问题,请参考以下文章

C# 怎样判断DEV GridView 中选中的哪一行是分组的标题行

在 Yii gridview 分页中保留复选框值

获取gridview中选中记录的超链接字段值

计算 React.js 中选中的复选框

如何获取UIPickerView中选中的cell的值

如何从C#中获取ListView中选中某一行某一列的值