Search code examples
c#asp.netweb-controls

How to retrieve a TextBox from DetailsView - ASP.NET


I have a DetailsView Control, inside as a template a TextBox. I need to find out the value for a TextBox when Inserting data Event handler-, _ItemInserting.

The script does not work. Ant ideas?? Thanks

-------------------- WEB FORM

<asp:TemplateField HeaderText="Profile" SortExpression="ContentAuthor">
                <ItemTemplate>
                    <asp:Label ID="uxContentAuthorDisplayer" runat="server" Text='<%# Bind("ContentAuthor") %>'></asp:Label>
                </ItemTemplate>
                <InsertItemTemplate>
                    <asp:TextBox ID="uxContentAuthorInput" runat="server" Text='<%# Bind("ContentAuthor") %>'></asp:TextBox>
                </InsertItemTemplate>
            </asp:TemplateField>

-------------------- CODE BEHIND

          protected void uxInsertAuthor_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            //// Find control on page
            TextBox myAuthorProfile = (TextBox)uxInsertAuthorInput.FindControl("uxContentAuthorDisplayer");
            // Set a default value in Data Base if field has been left empty (DB field NOT NULL)           
            if (string.IsNullOrEmpty(myAuthorProfile.Text))
            {
                string myAllert = "Field is NULL";
            }
            else
            {
                string myAllet = "Field is NOT NULL";
            }          
        }

Solution

  • Try using the FindControl method of your TemplateField container control (the DetailsView). For example, if your DetailsView is named "MyControl" try

    //// Find control on page
    TextBox myAuthorProfile = (TextBox)MyControl.FindControl("uxContentAuthorInput");
    

    Please Note

    You are using the ID of the Label control in your FindControl method and you are trying to cast it to a TextBox.