2012-11-07 69 views
3

我有一個gridview,我已經通過編程方式添加了複選框。 我做一個foreach循環內創建複選框時以下,從而使檢查時,他們觸發一個事件,只允許檢查一個複選框 - asp.net c#

  cbGV = new CheckBox(); 
      cbGV.ID = "cbGV"; 
      cbGV.AutoPostBack = true; 
      cbGV.CheckedChanged += new EventHandler(this.cbGV_CheckedChanged); 

所以基本上當我想事件被觸發的,我有以下以下,

protected void cbGV_CheckedChanged(object sender, EventArgs e) 
    { 
     //gets the current checked checkbox. 
     CheckBox activeCheckBox = sender as CheckBox; 

     foreach (GridViewRow gvr in GridView1.Rows) 
     { 
      //this code is for finding the checkboxes in the gridview. 

      CheckBox checkBox = ((CheckBox)gvr.FindControl("cbGV")); 

      //so basically, right here i'm confused on how i should compare the if/else logic, how i should compare and disable every other checkbox if the current checkbox is checked. Any ideas gues? 

     } 

感謝您的提前回答。

+0

你的問題是什麼? – Ahmad

+0

那麼,首先請說明爲什麼不使用單選按鈕而不是複選框?如果你堅持,那麼你可以使用jquery/javascript實現相同的功能。 –

+0

使用單選按鈕 –

回答

3

首先,您應該只選中其他CheckBoxes(如果這是你想要的),當這個CheckBox被選中,而不是當它被選中時。

其次,你可以使用==運算符將此複選框與別人比較:

CheckBox activeCheckBox = sender as CheckBox; 
if(activeCheckBox.Checked) 
{ 
    foreach (GridViewRow gvr in GridView1.Rows) 
    { 
     CheckBox checkBox = ((CheckBox)gvr.FindControl("cbGV")); 
     checkBox.Checked = checkBox == activeCheckBox; 
    } 
} 
+0

同樣的問題在這裏,它只適用於當我通過複選框向上,而不是向下。這可能是由於foreach循環的性質? – Mana

+0

你在哪裏動態創建了複選框?完美的地方在'RowCreated'中,而不是循環中。我可以問你爲什麼不把它們聲明地添加到aspx標記的TemplateField中嗎? –

+0

順便說一句,你可以解釋你寫的以下行, checkBox.Checked = checkBox == activeCheckBox; – Mana

0

我沒有嘗試,但在這裏是爲了做這件事:

protected void cbGV_CheckedChanged(object sender, EventArgs e) 
    { 
     //gets the current checked checkbox. 
     CheckBox activeCheckBox = sender as CheckBox; 
     BOOL flag = false; 
     CheckBox selectedCheckBox; 
     foreach (GridViewRow gvr in GridView1.Rows) 
     { 
      //this code is for finding the checkboxes in the gridview. 

      CheckBox checkBox = ((CheckBox)gvr.FindControl("cbGV")); 

      if (checkBox.Checked==true && flag==false) 
       { 
        flag = true; 
        selectedCheckBox = checkBox; 
       } 
      else 
       { 
        if (checkBox != selectedCheckBox) 
          { 
          checkBox.Enabled = false; 
          checkBox.Checked = false; 
          } 
       } 
      //so basically, right here i'm confused on how i should compare the if/else logic, how i should compare and disable every other checkbox if the current checkbox is checked. Any ideas gues? 

     } 
+0

配置嗨,這隻適用於當我通過複選框向上,而不是向下時。這可能是由於foreach循環的性質。任何想法如何解決這個問題? – Mana

0
CheckBox activeCheckBox = sender as CheckBox; 
// to uncheck all check box 
foreach (GridViewRow rw in GrdProc.Rows) 
{ 
    CheckBox chkBx = (CheckBox)rw.FindControl("ChkCust"); 
    if (chkBx != activeCheckBox) 
    { 
     chkBx.Checked = false; 
    } 
} 
相關問題