skip to Main Content

I have the following code in a ascx : I run a SQL query and I put it in a Datatable. Then I show the values in the page like this

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

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

<% next %>

Now… how can I set the ID of the checkbox dynamically?
something like

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

that obviously do not work.

I need to set the id as the value I get from the DB so if it is checked I can pass the checked id to another page.

2

Answers


  1. The problem is that row("MyId") returns type of object so you need to convert it to string to be able to bind it to Checkbox

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

    See: DataRow.Item[] Property

    Login or Signup to reply.
  2. Hum, would not a data control say like listview, or gridview be better here?

    You can have this markup:

            <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>
    

    Now to load we have this:

    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
    

    and we get this:

    enter image description here

    So, it is a lot less work to do the above.

    Even if you don’t have a bound check box, you can even feed the grid the data, and display a un-bound check box for selecting rows if that what you need/want.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search