views:

41

answers:

4

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.

+4  A: 

If 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.

Seshan
+1  A: 

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.

Dick Lampard
A: 

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.

Robbye Rob
+1  A: 

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.

Jamie
Good work.Beginners can easily understand this code snippet
Seshan