开发者

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>
  开发者_C百科      <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


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.


@jadarnel27 thank you for your information about putting the code in DataBound event. I had similar issue where a textbox value would only pass to DetailsView field (DefaultMode=Insert) with a button click event. I didn't want/need a button.

My scenario: code identifies if detailsview is needed (for insert). If record does not exist based on person selected from dropdown control, their PersonID is preloaded into the Person field of detailsview.

Using FindControl didn't work but using the following code did WHEN put in DataBound control.

// Get person selected from dropdown control and pass to DetailsView first row/cell
txtPerson.Text = Convert.ToString(ddlPersonSelect.SelectedValue);

TextBox tb = (TextBox)DetailsView1.Rows[0].Cells[1].Controls[0];
if (tb != null)
{
tb.Text = txtPerson.Text;
}

I hope this helps another newbie like me.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜