检查Gridview的前5行

时间:2017-09-08 05:17:40

标签: c# asp.net gridview checkbox

我有gridview显示来自sql表的大量行。我还在checkbox标头中有chkboxSelectAll gridview来检查gridview中的所有行。

chkboxSelectAll oncheckedchange的代码:

protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll");
            foreach (GridViewRow row in Grid.Rows)
            {
                CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");
                if (ChkBoxHeader.Checked == true)
                {
                    ChkBoxRows.Checked = true;
                }
                if (ChkBoxHeader.Checked == false)
                {
                    ChkBoxRows.Checked = false;
                }
            }
        }

但是,我只想检查标题复选框后检查前5行gridview。

我搜索的所有答案都是针对数据表或数据集但没有针对gridview本身。

有没有办法做到这一点。任何帮助将不胜感激.. !!

2 个答案:

答案 0 :(得分:4)

如果第二条评论的答案为真,那么这将是您的解决方案(例如):

    protected void chkboxSelectAll_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox ChkBoxHeader = (CheckBox)Grid.HeaderRow.FindControl("chkboxSelectAll");
        bool sign = ChkBoxHeader.Checked == true;
        int counter = 0;
        foreach (GridViewRow row in Grid.Rows)
        {
            CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");
            ChkBoxRows.Checked = sign;
            counter++;
            if (counter == 5)
            {
                break;
            }
        }
    }

答案 1 :(得分:1)

您可以使用LINQ来执行此操作:

foreach (GridViewRow row in Grid.Rows.Take(5))
{
    CheckBox ChkBoxRows = (CheckBox)row.FindControl("chkrow");
    if (ChkBoxHeader.Checked == true)
    {
        ChkBoxRows.Checked = true;
    }
    if (ChkBoxHeader.Checked == false)
    {
        ChkBoxRows.Checked = false;
    }
}