只允许选中一个复选框 - asp.net c#

时间:2012-11-07 09:58:58

标签: c# asp.net events gridview checkbox

我有一个gridview,我以编程方式添加了复选框。 我在foreach循环中创建复选框时执行以下操作,以便在选中时触发事件

            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?

        }

提前感谢您的回答。

3 个答案:

答案 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;
    }
}

答案 1 :(得分: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?

        }

答案 2 :(得分: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;
    }
}