3

我有一个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?

        }

提前感谢您的回答。

4

3 回答 3

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;
    }
}
于 2012-11-07T10:02:57.987 回答
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?

        }
于 2012-11-07T10:05:53.820 回答
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;
    }
}
于 2013-09-20T14:49:14.067 回答