相同绑定属性的两个不同控件?

时间:2013-08-28 01:55:07

标签: asp.net webforms asp.net-4.0

我正在尝试创建一个FormView,它在EditTemplate中可以根据其他标志显示一个文本框或下拉其中一个绑定属性:

<asp:FormView 
    id="EmailFormView" 
    runat="server" 
    DefaultMode="Edit" 
    DataSourceID="EmailDataSource"
    OnDataBound="EmailFormView_DataBound" 
>
    <EditItemTemplate>
        <asp:PlaceHolder ID="DelayHoursPlaceHolder" runat="server">
            <asp:TextBox CssClass="HoursBox" ID="ShortDelayTextBox" runat="server" Text='<%# Bind( "ShortDelay" ) %>' />
        </asp:PlaceHolder>
        <asp:PlaceHolder ID="DelayDropdownPlaceHolder" runat="server">
            <asp:DropDownList ID="ShortDelay" runat="server" SelectedValue='<%# Bind( "ShortDelay" ) %>'  
                DataValueField="Value" DataTextField="Text" DataSourceID="DropDownDataSource" />
        </asp:PlaceHolder>
    </EditItemTemplate>
</asp:FormView>

这适用于此代码:

protected void EmailFormView_DataBound( object sender, EventArgs e ) {
    var email = EmailObj;

    if (email.EmailType == EmailType.Type1) {
        EmailFormView.Row.FindControl("DelayHoursPlaceHolder").Visible = false;
        EmailFormView.Row.FindControl("DelayDropdownPlaceHolder").Visible = true;
    }
    else {
        EmailFormView.Row.FindControl("DelayHoursPlaceHolder").Visible = true;
        EmailFormView.Row.FindControl("DelayDropdownPlaceHolder").Visible = false;
        EmailFormView.Row.FindControl("DelayDropdownPlaceHolder").Controls.Clear();
    }
}

这可以很好地显示和隐藏适当的控件,但问题是当页面回发时,值会丢失。

有关如何使其发挥作用的任何想法?

1 个答案:

答案 0 :(得分:0)

确保在Page_Load事件中,您只在第一次加载页面时绑定下拉列表,如下所示:

protected void Page_Load(object sender, EventArgs e)
{
    if(!PostBack)
    {
        // Bind drop down list here
    }
}