简体   繁体   中英

Access dynamically created TextBox within a usercontrol which is in a DataList

i am using a datalist for showing dynamically generated controls, each control is in its respective usercontrol and i have used that user control in in the datalist item template

 <asp:DataList ID="dlCriteriaControl" runat="server" RepeatColumns="2" OnItemDataBound="dlCriteriaControl_ItemDataBound">
                                            <ItemTemplate>
                                                <%--<uc3:ucDatepicker ID="ucDatepicker1" runat="server" />
                                                <uc2:ucRadComboBox ID="ucRadComboBox1" runat="server" />--%>
                                                <uc1:ucTextBox ID="ucTextBox1" runat="server" Text='<%# Bind("Column_Name") %>' Prompt='<%# Bind("Column_Prompt") %>' />
                                                <uc3:ucDatepicker ID="ucDatePicker1" runat="server" Text='<%# Bind("Column_Name") %>'
                                                    Prompt='<%# Bind("Column_Prompt") %>' />
                                                <asp:HiddenField ID="hdnStatus" runat="server" Value='<%# Bind("Control_Display") %>' />
                                            </ItemTemplate>
                                        </asp:DataList>

In usercontrol i have given id to the textbox as txtName,and after dynamic generation of this textbox in datalist the id changes to txt+"the column name" eg. txtCaseCD with the help of property prompt

now when i want to access the textbox txtCaseCD i get object reference error or null

I am not sure how you are trying to access your control , but the following approach will guarantee you success. First find your user control.And then within the user control drill down to the required text box.

  protected void DataList_ItemDataBound(Object sender,DataListEventArgs e)
     {
           if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType ==   ListItemType.AlternatingItem)
 {
     ucTextBox myTextControl=(ucTextBox)e.Item.FindControl("ucTextBox1");
     if (myTextControl!= null)
      {
     TextBox txtCaseCD=(TextBox)myTextControl.Find("txtCaseCD");

      //now you can use txtCaseCD without a null reference error

      }

 }
 }

Let me know if this works in your setting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM