开发者

How do I initialize the controls in an InsertItemTemplate?

I have - for instance - an asp:FormView w开发者_如何学编程hich supports Read, Insert, Update, Delete and is bound to a DataSource:

<asp:FormView ID="FormView1" runat="server" 
    DataSourceID="ObjectDataSource1" >
    <ItemTemplate>
        <asp:Label ID="Label1" runat="server" Text='<%# Bind("MyText") %>' />
    </ItemTemplate>
    <EditItemTemplate>
        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("MyText") %>' />
    </EditItemTemplate>
    <InsertItemTemplate>
        <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("MyText") %>' />
    </InsertItemTemplate>
</asp:FormView>

If I am in Read-Mode or Edit-Mode the control is initialized with the property MyText of the current object which is bound to the FormView.

But when I go to Insert-Mode I do not have a "current object" (FormView1.DataItem is indeed null) and the controls are empty.

If I want to have my TextBox control initialized with a specific value how can I do that? In which event can I hook in to set default values to the controls in the InsertItemTemplate?

Especially I have in mind using an ObjectDataSource. I was expecting that the InsertItemTemplate is initialized with a business object which underlies my ObjectDataSource and which is created by the ASP.NET framework simply by using its default constructor when the InsertItemTemplate gets activated. In the default constructor I would init the class members to the default values I'd like to have in my controls of the InsertItemTemplate. But unfortunately that's not the case: No "default" object is created and bound to the FormView. So it seems I have to initialize all controls separately or to create the default object manually and bind it to the InsertItemTemplate of the FormView. But how and where can I do that?

Thanks in advance!


Try the ModeChanged event.

Therein you can use

TextBox _tb = this.FormView1.FindControl("TextBox1") as TextBox
if(_tb != null)
{
  _tb.Text = Mybusinessobject.property;
}

If .FindControl does return null, try to this:

this.FormView1.DataBind();
TextBox _tb = this.FormView1.FindControl("TextBox1") as TextBox
if(_tb != null)
{
  _tb.Text = Mybusinessobject.property;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜