views:

212

answers:

1

I have - for instance - an asp:FormView which 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!

A: 

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;
}
citronas
Thanks for this idea! I've used now a similar code in the DataBound event checking `if (FormView1.CurrentMode == FormViewMode.Insert)` which also seems to work. I was looking more for an option to bind a complete (default initialized) business object to the FormView but I don't see a way. It seems I have to init control by control.
Slauma