2013-03-20 148 views
1

我有一个gridview,我在每行中使用复选框。我试图访问每一行的复选框,并试图找出哪些复选框已checked.buut当我尝试运行下面的code.the条件总是假的,内部如果条件是从来没有达到code.kindly提前帮助我。访问gridview中选中的复选框

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

回答

2

的代码看起来不错。
问题可能是你在页面加载时绑定了gridview。
尝试电网页面加载的以下部分结合

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

} 
+0

haan shekhar那是原来的问题。谢谢男人 – Robin 2013-03-20 05:29:54

+0

@Robin不客气 – 2013-03-20 05:56:21

0

我只能猜测你绑定你的每页加载gridview没有检查回发。这会导致复选框失去当前状态。所以,你在哪里分配数据源到GridView,检查回发,如:

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

,你也可以做一些小的改进在你的代码就像你的检查:

if(chk.Checked == true) 

可以被替换为:

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

您可以省略多个字符串变量进行连接。它的更好,如果你使用StringBuilder(见why it is better因此您的代码将是:

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"); 
} 
0
if(!Page.IsPostBack) 
{ 
    // 
} 

回传起着CS文件重要作用。如果您在页面加载时清除值,则您将选中空值。 你的代码很好。 只是试图做到这一点...