0

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!

insomnium_
  • 1,800
  • 4
  • 23
  • 39

1 Answers1

1

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...
    }
}
Oliver Spryn
  • 16,871
  • 33
  • 101
  • 195
antar
  • 510
  • 1
  • 3
  • 16
  • That's why I'm stuck. If I DataBind every time page loads, I can't get CheckBox values. If I use !IsPostBack -> row.DataItem == null ,so I can't get row's data. – insomnium_ Feb 05 '12 at 18:52
  • Please, explain, how I'm supposed to get all the row data? – insomnium_ Feb 05 '12 at 18:57
  • gvRow.Cells[1].ToString() gives me "System.Web.UI.WebControls.DataControlFieldCell", not the containing value. – insomnium_ Feb 05 '12 at 19:44
  • I tried to use foreach(var row in GridView.Rows) var myObject=row.DataItem; But DataItem = null – insomnium_ Feb 05 '12 at 19:51
  • It should be gvRow.Cells[1].Text, sorry abt that – antar Feb 05 '12 at 20:06
  • Hmm, it works, but only if there are no controls in the cell. I know, I can use FindControl() in that case, but is access to cells the best practice of getting data from GridView rows? Thank you for your effort! – insomnium_ Feb 05 '12 at 20:09
  • I have used the method that I explained without any problem and other sources also recommend the same solution. Other way I can think of is by storing keys from each of checked rows and searching them back in datasource. However, this involves more work. Please share if you find any other practice so that I can learn :). Thanks! – antar Feb 06 '12 at 06:16