Skip to main content
 首页 » 编程设计

c#之ASP 复选框的 'checked' 属性总是返回 false

2024年02月23日24bonelee

我最近将一个“DataList”控件移到了一个 UserControl 中,并在我的 ASPX 页面上引用了它。 DataList 包含复选框,这些复选框具有最初由数据源分配的选中属性。

<asp:DataList ID="dlspec" CssClass="specs" runat="server" GridLines="Vertical" OnItemDataBound="dlspec_ItemDataBound"> 
    <FooterStyle BackColor="#CCCCCC" /> 
    <AlternatingItemStyle CssClass="alt-grey" /> 
    <SelectedItemStyle BackColor="#000099" Font-Bold="True" ForeColor="White" /> 
    <HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" /> 
      <ItemTemplate> 
          <table> 
            <tr> 
              <td class="leftcol"> 
                 <asp:Label ID="lblDimension" runat="server" Text='<%# Eval("Dimension") %>'></asp:Label>: 
               </td> 
               <td class="ProductDetailData"> 
                    <asp:Label ID="lblName" runat="server" Text='<%# Eval("Attribute") %>'></asp:Label> 
               </td> 
               <td class="find-similar"> 
                 <asp:CheckBox ID="FindSimilarCheckbox" runat="server" Checked='<%# Eval("CheckBox")=="true"? true:false %>' Text='<%# Eval("AttributeID") %>' Visible='<%# Eval("CheckBoxState")=="0"? true:false %>' /> 
                </td> 
              </tr> 
            </table> 
         </ItemTemplate> 
       </asp:DataList> 

现在,在用户控件绑定(bind)到的“aspx”中的按钮单击事件上,我尝试获取复选框的“选中”属性以通过一些逻辑。 我基本上使用下面的代码来查找用户控件并循环遍历其中的控件。

Control SpecsPanel = FindSimilarPnl.FindControl("Specifications").FindControl("dlspec"); 
foreach (Control ct in SpecsPanel.Controls) 
        GetCheckedAttributes(ct, ref qry); 

然而,在我将数据列表移至用户控件后,复选框的“已选中”属性始终变为“假”。有什么想法吗?我错过了什么愚蠢的东西吗?非常感谢任何想法。让我知道如果我需要添加更多代码以便您更好地理解。 谢谢

请您参考如下方法:

我发现了为什么会这样……要回答我自己的问题。 所以模板中的 CheckBox ID 是“FindSimilarCheckBox”,它在数据绑定(bind)时被重命名。因此,当发生回发时,服务器将所有复选框的 ID 返回为“FindSimilarCheckBox”,并且所有内容的 Checked 属性均为 false。我不得不重新数据绑定(bind)用户控件,这次放入一个条件来检查它是否是回发操作以及复选框的唯一 ID 是否存在于 Request.Form 集合中,以便在 chkbox 上设置 Checked 属性。像这样的东西:

protected void dlspec_ItemDataBound(object sender, DataListItemEventArgs e) 
 { 
    var ck = e.Item.FindControl("FindSimilarCheckbox") as CheckBox; 
            if (ck != null) 
            { 
                ck.ID = ck.Text; 
                ck.Text = ""; 
                //EDIT: Karthik - Since we moved the Specifications in to user control, check if this a postback , then check to see the CheckBox state on the form while posting back 
                if(IsPostBack && Request.Form[ck.UniqueID] != null) 
                { 
                    ck.Checked = true; 
                } 
 } 

我的问题现在已经解决了。希望这个答案可以帮助您了解导致我的问题的原因。让我知道是否需要提供更多详细信息。