2012-08-27 25 views
0

我正在使用ASP.NET開發的應用程序,我面對的問題是使用FormView控件,FormView控件有ItemTemplate,InsertItemTemplate和EditItemTemplate。如何在FormView控件中獲取所選值?

下面是InsertItemTemplate元素的代碼片段:

<asp:FormView ID="FormView1" runat="server" DefaultMode="ReadOnly"> 
    <InsertItemTemplate> 
     <table cellpadding="0" cellspacing="0"> 
      <tr> 
       <td> 
        <asp:Label id="lblPS" runat="server" Text="Process Status"></asp:Label> 
       </td> 
       <td> 
        <asp:DropDownList ID="ddlPS" runat="server"></asp:DropDownList> 
       </td> 
      </tr> 
      <tr> 
       <td> 
        <asp:Label id="lblAP" runat="server" Text="Action Plan"></asp:Label> 
       </td> 
       <td> 
        <asp:TextBox id="txtAP" runat="server" Width="230px" TextMode="MultiLine" Rows="5"></asp:TextBox> 
       </td> 
      </tr> 
      <tr> 
       <td colspan="2"> 
        <asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /> 
       </td> 
      </tr> 
     </table> 
    </InsertItemTemplate> 
</asp:FormView> 

在Page_Load事件中,我做的數據源綁定到的DropDownList如下:

FormView1.ChangeMode(FormViewMode.Insert); 

DropDownList ddlPS = FormView1.FindControl("ddlPS") as DropDownList; 
ddlPS.DataSource=GetProcessStatus(); 
ddlPS.DataBind(); 
ddlPS.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- Please Select -", "- Please Select -")); 

數據綁定到DropDownList中和「 - 請選擇 - 「沒問題。

這裏的問題出現了,當提交按鈕點擊時,我想讓用戶選擇DropDownList的值,但DropDownList.SelectedItem.Text總是返回我「 - 請選擇 - 」。

請指教如何在InsertItemTemplate中獲取用戶選定的值。

回答

1

問題出在你頁面上的DataBind事件中。 當你DataBind你清除現有的值,因此失去選定的價值。

下拉列表會記住其中的項目,因此您不需要在每次回發時都進行DataBind。

你可能應該是這樣的。

protected void Page_Load(object sender, EventArgs e) 
{ 
    if(!IsPostBack) 
    { 
    DropDownList ddlPS = FormView1.FindControl("ddlPS") as DropDownList; 
    ddlPS.DataSource=GetProcessStatus(); 
    ddlPS.DataBind(); 
    ddlPS.Items.Insert(0, new System.Web.UI.WebControls.ListItem("- Please Select -", "- Please Select -")); 
    } 
} 
相關問題