Search code examples
c#asp.nettextboxdetailsview

Access Textbox inside DetailsView


Does anyone have any idea how I can set the text of a textbox inside a DetailsView field (c#)?

I've tried a few variations but all return out of context and object reference not set errors.

Heres my code...

ASPX:

<asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px">
    <Fields>
        <asp:TemplateField HeaderText="Header Text">
            <InsertItemTemplate>
                <asp:TextBox ID="TextBox1" runat="server" Text="test"></asp:TextBox>
            </InsertItemTemplate>
        </asp:TemplateField>
    </Fields>
</asp:DetailsView>

CS:

TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
txt.Text = "Text ";

Cheers


Solution

  • That error likely means that there is nothing in your DetailsView yet. I bet if you put this in your code:

    TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1");
    if (txt != null)
    {
        txt.Text = "Text ";
    }
    

    You'll see that txt is, in fact, null - this is because the FindControl method didn't find anything named "TextBox1" in the DetailsView.

    You need to move this code to a point where you know the DetailsView has been populated (if it's bound to a DataSource, you could do this in the DataBound event of your DetailsView).

    Also, I noticed that your TextBox is in an InsertItemTemplate. You won't find that TextBox1 until you put the DetailsView in edit mode, either by default:

    <asp:DetailsView ID="DetailsView1" runat="server" Height="50px" Width="125px"  
            DefaultMode="Insert">
    

    Or in code behind:

    DetailsView1.ChangeMode(DetailsViewMode.Insert);
    TextBox txt = (TextBox)DetailsView1.FindControl("TextBox1"); 
    txt.Text = "Text "; 
    

    Hopefully that helps.