sams5817
sams5817

Reputation: 1037

How to get Selected Value in FormView Control?

I'm working with an application develop by ASP.NET, the problem I face is using FormView control, the FormView Control has ItemTemplate, InsertItemTemplate and EditItemTemplate.

Below is the code fragment of 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>

In Page_Load event, I do DataSource Binding into the DropDownList as below:

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 -"));

The data binding into DropDownList and the "- Please Select -" was ok.

Here the problem comes, when Submit Button click, I wanted to get user selected DropDownList Value, but the DropDownList.SelectedItem.Text always return me "- Please Select -".

Please advise how can I get the user selected value in InsertItemTemplate.

Upvotes: 0

Views: 4787

Answers (1)

nunespascal
nunespascal

Reputation: 17724

The problem is with your DataBind on Page Load event. When you DataBind you clear the existing values and hence loose the selected value.

A drop down list remembers the items in it, so you don't need to DataBind on every postback.

Your could should be like this.

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 -"));
  }
}

Upvotes: 1

Related Questions