Home > Software design >  How to dynamically assign ID to a checkbox in a for-each cycle
How to dynamically assign ID to a checkbox in a for-each cycle

Time:10-27

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 dymanically? 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.

CodePudding user response:

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

  • Related