Retrieving an ID from a dynamically created control?

Posted on 2011-05-08
Last Modified: 2012-05-11
I am building an HTML Table dynamically to show records. It's essentially a grid of data. The first cell of each row contains a checkbox which is dynamically created the same time the table is. This checkbox is used to select the record for editing. My question is, how can I check when a checkbox is checked so I can retrieve a record. I'm using VB.Net but thinking Javascript would work. I'm just not real good with Javascript.

Question by:BlakeMcKenna
    LVL 2

    Expert Comment

    Option 1
    <asp:GridView ID="GridView1" runat="server" AllowPaging="True" 
       AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="PersonID" 
       DataSourceID="mySource" Width="366px" CellPadding="4" 
       ForeColor="#333333" GridLines="None">
       <asp:CommandField ShowSelectButton="True" />
       <asp:BoundField DataField="PersonID" HeaderText="PersonID" 
             InsertVisible="False" ReadOnly="True" SortExpression="PersonID" />
       <asp:BoundField DataField="Name" HeaderText="Name" 
                                           SortExpression="Name" />
       <asp:TemplateField HeaderText="Select">
           <asp:CheckBox ID="chkSelect" runat="server" />
     <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
     <RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
     <PagerStyle BackColor="#FFCC66" ForeColor="#333333" 
                               HorizontalAlign="Center" />
     <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
     <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
     <AlternatingRowStyle BackColor="White" />
    Now in the button click event, write this code:
    // StringBuilder object
    StringBuilder str = new StringBuilder();
    // Select the checkboxes from the GridView control
    for (int i = 0; i < GridView1.Rows.Count; i++)
      GridViewRow row = GridView1.Rows[i];
      bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked;
      if (isChecked)
        // Column 2 is the name column
    // prints out the result

    Open in new window

      <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this);" 
                  runat="server" type="checkbox" />
    SelectAllCheckboxes JavaScript method:
    <script language="javascript">
     function SelectAllCheckboxes(spanChk){
       // Added as ASPX uses SPAN for checkbox
       var oItem = spanChk.children;
       var theBox= (spanChk.type=="checkbox") ? 
            spanChk : spanChk.children.item[0];
         if(elm[i].type=="checkbox" && 

    Open in new window

    LVL 2

    Expert Comment

    option 2:
    protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
      CheckBox c = e.Row.Cells[4].FindControl("YourCheckboxId");
      if(c != null && e.Row.DataItem["sFixed_f"] == true)
        c.Checked = true;

    Open in new window

    LVL 2

    Accepted Solution

    The following will trigger a post back with the id of the record:
    Since you are dynamically creating the checkbox - make sure to set the value (DB_ID below) to the correct database id.

    <html xmlns="">
    <head runat="server">
        <script type="text/javascript">
            function EnterEditMode(id) {
                //Do something here to enter edit mode - assuming a postback
                __doPostBack('FakePostBackButton', id);
        <form id="form1" runat="server">
                        <input type="checkbox" value="DB_ID" onclick="EnterEditMode(this.value)" />
            <asp:Button ID="FakePostBackButton" runat="server" OnClick="ServerPostBackHandler" style="display: none;" />

    Open in new window

    void FakePostBackButton_Click(object sender, EventArgs e)
        //Get ID passed in as argumnet of __doPostBack
        int id = Convert.ToInt32(Request["__EVENTARGUMENT"]);
        //Lookup record

    Open in new window


    Author Comment

    None of these proposed solutions are viable.
    LVL 2

    Expert Comment

    You should probably come up with a solution more viable than dynamically generating HTML then.... lol

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Do You Know the 4 Main Threat Actor Types?

    Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

    Welcome my friends to the second instalment and follow-up to our Minify and Concatenate Your Scripts and Stylesheets (…
    A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
    how to add IIS SMTP to handle application/Scanner relays into office 365.
    In this sixth video of the Xpdf series, we discuss and demonstrate the PDFtoPNG utility, which converts a multi-page PDF file to separate color, grayscale, or monochrome PNG files, creating one PNG file for each page in the PDF. It does this via a c…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    10 Experts available now in Live!

    Get 1:1 Help Now