在Gridview中仅获取选定的行数 [英] get only selected rows count in Gridview

查看:75
本文介绍了在Gridview中仅获取选定的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个gridview我可以通过
获取总记录数 下面的代码

Hi,

I have a gridview i can get the total records count by
below code

GridView1.Rows.count

,但在我的网格中,我有复选框,并且在网格外有一个按钮.当我单击按钮时,我只想获取带有网格中复选框的选定行的计数.我们该怎么做?

在此先感谢

but in my grid i have check boxes and i have a button out side the grid. when i click on the button i want to get the count of only selected rows with checkboxes in the grid. how can we do that?

Thanks in Advance

推荐答案

protected void Button2_Click(object sender, EventArgs e)
    {
        if (GridView1.Rows.Count > 0)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                //finding checkbox in GridView
                CheckBox cbx = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
                //CheckBox not null
                if (cbx != null)
                {
                    //if CheckBox Checked
                    if (cbx.Checked)
                    {
                        //add your logic here.
                        //this is for example to get first column values of selected CheckBox
                        string firstColumnValue = GridView1.Rows[i].Cells[0].Text;
                        Response.Write(firstColumnValue);
                    }
                }
            }
        }
    }


您需要遍历网格的所有行.
1.在每一行中找到复选框控件
2.查找复选框的状态.如果不满意,则增加计数器.

循环结束后,将计数显示为选定的行数.
You need to loop through all the rows of the Grid.
1. Find the checkbox control in each row
2. Find the state of checkbox. If chekced then increment the counter.

Once loop ends, show the count as selected number of rows.


在YourForm.aspx.cs
中创建一个公共的Static方法.
Create a public Static method in YourForm.aspx.cs
public static String CreateCheckBox(Int32 index)
{
    ///Return a checkbox created with dynamic ID
    return "<input type="\"checkbox\"" id="\"Chk_"" index="" hold=" /> " onclick="\"checkSelection()\"" />";
}



在gridView中创建一个项目模板...就像这样



Create a item template in gridView... like this

<TemplateField HeaderText="">
<ItemTemplate HorizontalAlign="Left" />
<ItemTemplate>
<%#YourNamespace.YourForm.CreateCheckBox(Container.DisplayIndex)%>
</ItemTemplate>
</TemplateField>



添加复选框的javascript函数(单击时)



Add the javascript function (On click) of the checkboxes

function checkSelection() {
var nMarked = 0;
for (var i = 0; i < document.forms[0].elements.length; i++) {
if (document.forms[0].elements[i].checked &&
document.forms[0].elements[i].name.indexOf('Chk_') > -1) {
    nMarked = nMarked + 1;
}
}
if (nMarked == 0) {
    alert("no element has been selected");
    return;
 }
else
{
    alert("You have selected " + nMarked + " checkboxes");
    //Do other stuff here
}
}



告诉我发生了什么事;)



tell me what hapened ;)


这篇关于在Gridview中仅获取选定的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆