accessing selected checkboxes in gridview

倾然丶 夕夏残阳落幕 提交于 2019-12-24 15:25:53

问题


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");
}

回答1:


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

}



回答2:


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");
}



回答3:


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



来源:https://stackoverflow.com/questions/15515279/accessing-selected-checkboxes-in-gridview

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!