1

i have a gridview in which i am using checkbox in each row. i am trying to access checkbox of each row and trying to find out which checkboxes have been checked.buut when i try to run the below code.the condition always stands to be false and the inner if condition is never reached by the code.kindly help me.thanks in advance.

protected void btn_3id_Click(object sender, EventArgs e)
{
    string str = "";
    string srr = "";
    for (int i = 0; i < GridView1.Rows.Count;i++ )
    {
       CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
       if (chk.Checked==true)     
       {         
           if (str == "")    
           {
              str = GridView1.Rows[i].Cells[0].Text.ToString();
           }     
           else     
           {         
              srr = str + "," + GridView1.Rows[i].Cells[0].Text.ToString();  
           } 
        }
    }
    Session["Card_id"] = str;
    Response.Redirect("ID.aspx");
}
Habib
  • 219,104
  • 29
  • 407
  • 436
Robin
  • 471
  • 6
  • 18

3 Answers3

2

The code looks fine.
The problem could be you are binding the gridview at page load.
Try grid binding in the following section of page load

if(!Page.IsPostBack)
{
  //code to bind the gridview

}
शेखर
  • 17,412
  • 13
  • 61
  • 117
0

I can only guess that you are binding your gridview on each page load without checking PostBack. That is causing the checkbox to loose its current state. So where you are assigning the DataSource to the Gridview , Check for PostBack like:

if(!Page.IsPostBack)
{
   GridView1.DataSource = yourDataSource;
   GridView1.DataBind();
}

also you can do some minor improvements in your code like your check:

if(chk.Checked == true)

can be replaced as:

if(chk.Checked) //Since it returns a bool value. 

You can omit multiple string variables for concatenation. Its better if you use StringBuilder, (See why it is better) so your code would be:

protected void btn_3id_Click(object sender, EventArgs e)
{
    StringBuilder sb  = new StringBuilder();
    for (int i = 0; i < GridView1.Rows.Count;i++ )
    {
       CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("CheckBox1");
       if (chk.Checked==true)     
       {         
              sb.Append() GridView1.Rows[i].Cells[0].Text.ToString();
       }     
    }
    Session["Card_id"] = sb.ToString();
    Response.Redirect("ID.aspx");
}
Community
  • 1
  • 1
Habib
  • 219,104
  • 29
  • 407
  • 436
0
if(!Page.IsPostBack)
{
  //
}

Postback plays important role in cs file. If you are clearing values on page load , you will null values of checkbox. You code is fine. Just try to do this...

शेखर
  • 17,412
  • 13
  • 61
  • 117
Niks
  • 997
  • 2
  • 10
  • 28