复选框检查更改后,将删除动态生成的复选框

时间:2014-08-13 09:36:29

标签: asp.net

我根据在文本框中输入的文本动态生成复选框。如果选中任何复选框\取消选中,则会删除该复选框。当我检查元素时,我找不到复选框,并且不会触发其更改事件。所有这些控件都在更新面板中。 代码如下:

   <ajax:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Conditional">
   <ContentTemplate>
   <table>
   <tr>
     <td>
       <asp:TextBox ID="txtProducts" runat="server" AutoPostBack="true" onblur="return validate();" OnTextChanged="txtProducts_TextChanged"></asp:TextBox>
     </td></tr>
   <tr>
     <td>
        <panel runat="server" id="panelDynamicCheckbox"></panel>
     </td>
   </tr>
   </table>
  </ContentTemplate>
   <Triggers>
        <ajax:AsyncPostBackTrigger ControlID="txtProducts" EventName="TextChanged" />
    </Triggers>
   </ajax:UpdatePanel>

代码背后:

    protected void txtProducts_TextChanged(object sender, EventArgs e)
    {
        string[] products = txtProducts.Text.Split(',');
        CheckBox[] chk = new CheckBox[products.Length];
        int countForCheckbox = 0;
        foreach (string product in products)
        {
            chk[countForCheckbox] = new CheckBox();
            chk[countForCheckbox].ID = product;
            chk[countForCheckbox].Text = product;
            chk[countForCheckbox].Checked = true;
            chk[countForCheckbox].AutoPostBack = true;
            chk[countForCheckbox].EnableViewState = true;
            chk[countForCheckbox].CheckedChanged += new EventHandler(Dynamic_CheckChanged);
            panelDynamicCheckbox.Controls.Add(chk[countForCheckbox]);
                countForCheckbox++;
        }
    }

    protected void Dynamic_CheckChanged(object sender, EventArgs e)
    {        
        CheckBox checkbox = (CheckBox)sender;
        lblProductDetails.Text = "Done";
    }

在textchange上显示复选框,但是当我取消选中复选框时会被删除。

1 个答案:

答案 0 :(得分:0)

我得到了答案。 在回发时动态创建的元素被删除所以在回发时我必须再次生成元素。所以在page_load中我做了以下操作:

   protected void Page_Load(object sender, EventArgs e)
   { 
      if (IsPostBack)
      {
        CheckBox[] chk = new CheckBox[products.Length];
        int countForCheckbox = 0;
        panelDynamicCheckbox.Controls.Clear();
        foreach (string product in products)
        {
            chk[countForCheckbox] = new CheckBox();
            chk[countForCheckbox].ID = product;
            chk[countForCheckbox].Text = product;
            chk[countForCheckbox].Checked = true;
            chk[countForCheckbox].AutoPostBack = true;
            chk[countForCheckbox].EnableViewState = true;
            chk[countForCheckbox].CheckedChanged += new EventHandler(Dynamic_CheckChanged);
            panelDynamicCheckbox.Controls.Add(chk[countForCheckbox]);
            countForCheckbox++;
        }
      }
   }