Getting data from GridView on Button_Click

insomnium_ picture insomnium_ · Feb 5, 2012 · Viewed 11.5k times · Source

My problem is:

I have a GridView, which is bound to list of declared DTO objects with column of CheckBoxes. Also, I have a "Save" button on the page. My mission concludes in getting all rows, where CheckBox is checked and get the containing data. Unfortunately, row.DataItem = null on Button1_Click, because, I'm using if(!IsPostBack) gw.DataBind() statement (otherwise, I can't get CheckBox status). Could you give me the best practice for solving my problem?

Thank you in advance!

Answer

antar picture antar · Feb 5, 2012

If you do if(!IsPostBack) --> gw.DataBind(), that will reinitialize your GridView and the checkboxes will be set to unchecked again.

In your case, in Button1_Click event, you can loop through each DataRow on your GridView and find the row which has it's checkbox checked and get all the selected row data.

foreach (GridViewRow gvRow in gw.Rows) {
// Find your checkbox
    CheckBox chkBox = (CheckBox)gvRow.FindControl("checkBox");

    if (chkBox.Checked) {
    // Get your values 
        string value1 = gvRow.Cells[1].Text;
        string value2 = gvRow.Cells[2].Text;
        // etc...
    }
}