Getting Checked rows from gridview in asp.net

2019-02-10 16:17发布

问题:

I have a GridView in ASP.net where I have a CheckBox column. The user can toggle the CheckBox. Now, what I want is that when the user clicks on a button, all the records from the GridView where the CheckBox is checked should be displayed. And on another button, the opposite state should be displayed...
I am not getting the logic for the same.

Can anyone please help me with the logic..

回答1:

You could iterate through the GridViewRows and check if the CheckBox is checked using something like the following

Edit from comments, fixed small bugs. Thanks guys. (3/20/2013):

foreach (GridViewRow row in yourGridViewID.Rows)
{
    CheckBox check = (CheckBox)row.FindControl("CheckBoxName");

    if (check.Checked)
    {
        //Take Row information from each column (Cell) and display it
    }
    else
    {
        //Display in seperate area
    }
}

The index is going to be the column number starting from 0, going left to right of which column holds the CheckBox. You need to make sure the CheckBox has an ID name which is used at CheckBoxName. If you don't have an ID for that, you can also use

CheckBox check = (CheckBox)row.Cells[index].Controls[0];