2013-08-30 36 views
1

我有一個gridview,其中包含模板字段中的複選框。我想要檢索複選框被選中的行的值,以便我可以通過數據庫更新它們。這裏是我的代碼:使用複選框從gridview中選擇單獨的行

protected void approve_Click(object sender, EventArgs e) 
    { 
     for (int i = 0; i < GridView1.Rows.Count; i++) 
     { 
      if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked) 
      { 

//我想如果循環發現選中的複選框,將執行以下到該行:

   con.Open(); 

       string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + ""; 

       SqlCommand scmapprove = new SqlCommand(approve, con); 

       scmapprove.ExecuteNonQuery(); 

       view(); 

       con.Close(); 

      } 

          } 

然而,它似乎並沒有工作。例如,我從表中檢查了五行,它只更新第一行。我該怎麼辦?

+0

您是否將ID綁定到第二列或第一列?你的代碼看起來很好!難道你需要'GridView1.Rows [i] .Cells [0] .Text'? – afzalulh

+0

嗨afzalulh,我試過了,它說ID無法找到。我認爲這是因爲複選框在第0行? – wormwood

+0

什麼是'view();'?你是否用這個重新綁定了Gridview? – afzalulh

回答

2

您正在重新查找一個檢查行後的Gridview。在完成所有更新操作後綁定它:

protected void approve_Click(object sender, EventArgs e) 
{ 
    for (int i = 0; i < GridView1.Rows.Count; i++) 
    { 
     if (((CheckBox)GridView1.Rows[i].FindControl("Select")).Checked) 
     { 
      //I thought if the loop finds a checked check box, it will execute the following to that row: 
      con.Open(); 
      string approve = "update table set status ='Approved' where ID=" + GridView1.Rows[i].Cells[1].Text + ""; 

      SqlCommand scmapprove = new SqlCommand(approve, con); 
      scmapprove.ExecuteNonQuery(); 

      //view(); //Donot rebind the gridview now. 
      con.Close(); 
     } 
    } 

    view(); 
} 
相關問題