I have a GridView
. I have to collect the GridViewRow
where checkbox is selected. How can I achieve it without any client side script? Please help me to get this done.
views:
41answers:
4If you are familiar with LINQ,you can get this something like
List<GridViewRow> rowCollection =
GridView1.Rows
.OfType<GridViewRow>()
.Where(x => ((CheckBox)x.FindControl("chkRow")).Checked)
.Select(x => x).ToList();
All the best.
Alternative old-school method is to iterate through the Rows collection of the grid with for or foreach cycle, find the checkboxes with the FindControl method and check their Checked property value.
I know that this is not an answer, but because of View State and how the control is initially loaded on the page init. The state may not have the information you are looking for, so creating a business object to hold this data based on the control's events may be better. The LINQ statement is great and LINQ is so much easier to do instead of iterating through the control rows.
Always remember that the state of the control has to be saved so that the interaction is not lost on the post back.
Simple and easy to understand when you come back to it later.
var selectedRows = (from GridViewRow row in GridView1.Rows
let cbx = (CheckBox)row.FindControl("CheckBox1")
where cbx.Checked
select row).ToList();
Bare in mind that for this to work I think you'll need to convert the column containing the checkbox into a template column.