【问题标题】:How to dynamically assign ID to a checkbox in a for-each cycle如何在for-each循环中为复选框动态分配ID
【发布时间】:2021-12-11 16:28:15
【问题描述】:

我在 ascx 中有以下代码:我运行 SQL 查询并将其放入数据表中。然后我像这样在页面中显示值

<% For each row As DataRow In myDataTable.Rows %>

    <%=row("something") %>
    <%=row("somethingelse") %>
    <asp:CheckBox ID="CheckBox1" runat="server" />

<% next %>

现在...如何动态设置复选框的 ID? 像

<asp:CheckBox ID="<%=row("MyId")%>" runat="server" />

这显然行不通。

我需要将 id 设置为从数据库获取的值,因此如果选中它,我可以将选中的 id 传递到另一个页面。

【问题讨论】:

    标签: asp.net vb.net checkbox datatable


    【解决方案1】:

    问题在于row("MyId") 返回的类型为object,因此您需要将其转换为string 才能将其绑定到复选框

    <asp:CheckBox ID="<%=row('MyId').ToString()%>" runat="server" />
    

    见:DataRow.Item[] Property

    【讨论】:

      【解决方案2】:

      嗯,数据控件不是说像listview,或者gridview这样更好吗?

      你可以有这个标记:

              <asp:GridView ID="GVHotels" runat="server" class="table" AutoGenerateColumns="false">
                  <Columns>
                      <asp:BoundField DataField="FirstName"   HeaderText="FirstName"  />
                      <asp:BoundField DataField="LastName"    HeaderText="LastName"   />
                      <asp:BoundField DataField="City"        HeaderText="City"       />
                      <asp:BoundField DataField="HotelName"   HeaderText="HotelName" HeaderStyle-Width="200"   />
                      <asp:BoundField DataField="Description" HeaderText="Description" />
      
                      <asp:TemplateField HeaderText="Active"  ItemStyle-HorizontalAlign="Center"  >
                          <ItemTemplate>
                              <asp:CheckBox ID="ckActive" runat="server" 
                                  Checked=<%# Eval("Active") %>   />
      
                          </ItemTemplate>
                      </asp:TemplateField>
      
                  </Columns>
              </asp:GridView>
      

      现在加载我们有这个:

      Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      
          If Not IsPostBack Then
      
              Dim strSQL As String =
                  "SELECT TOP 10 FirstName, LastName, HotelName, City, Description, Active
                   FROM tblHotels WHERE description is not null ORDER BY HotelName"
      
              GVHotels.DataSource = MyRst(strSQL)
              GVHotels.DataBind()
      
          End If
      
      End Sub
      

      我们得到了这个:

      所以,做上面的工作要少很多。

      即使您没有绑定复选框,您甚至可以向网格提供数据,并显示一个未绑定的复选框以选择您需要/想要的行。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-25
        • 2013-06-02
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        • 2012-09-20
        • 1970-01-01
        • 2012-12-24
        相关资源
        最近更新 更多