ASP.NET and C# - Get selected item in static DropDownList

huong picture huong · Jun 7, 2012 · Viewed 14.8k times · Source

I'm new to ASP.NET and I'm having problem with getting selected item in static DropDownList. This is the structure of my list:

                   <asp:DropDownList ID="txtGender" runat="server">
                            <asp:ListItem>Male</asp:ListItem>

                            <asp:ListItem>Female</asp:ListItem>

                            <asp:ListItem>Other</asp:ListItem>

                            <asp:ListItem>Rather not say</asp:ListItem>
                    </asp:DropDownList>

Then in the code where I want to get the selected item, I use txtGender.SelectedItem and always get the first item as input. I have another DropDownList where I have to fetch the items from database, then I use IsPostBack before calling DataBind() and it works fine. So I'm wondering how should I use IsPostBack in static DropDownList as above? Please help.

*EDITED

Below is the method that I use the txtGender:

protected void btnSave_Click(object sender, EventArgs e)
{
    int uID= int.Parse(Session["uID"].ToString());
    PhotoDataSetTableAdapters.MembersTableAdapter memAdap = new PhotoDataSetTableAdapters.MembersTableAdapter();
    PhotoDataSet.MembersDataTable memTable = memAdap.GetMemberByID(uID);

    DataRow[] dr = memTable.Select("userID = " + uID);
    string Fname = memTable.AsEnumerable().Single().Field<String>("avatar");
    if(PhotoUploader.HasFile)
    {
       Fname = Path.GetFileName(PhotoUploader.FileName);
       PhotoUploader.SaveAs(Server.MapPath("~/avatar/") + Fname);
    }

    string newPass = memTable.AsEnumerable().Single().Field<String>("password");
    if (txtPass.Text != "")
    {
        newPass = txtPass.Text;
    }

    string tmp = txtBday.Text;
    DateTime bday = DateTime.ParseExact(tmp, "dd/MM/yyyy", null);

    memAdap.UpdateMemberProfile(newPass, txtEmail.Text, txtRealname.Text, txtLocation.Text, txtGender.SelectedItem.Text, txtBio.Text, bday, Fname, uID);
    //Response.Write(txtGender.SelectedItem.Text + " " + txtBio.Text);
    Response.Redirect("Photostream.aspx");
}

P.s: I tried using Response.Write to see the input for gender but it's always the first item of the list to be selected. I also have no input for txtBio even though everything seems alright.

Answer

Josh Mein picture Josh Mein · Jun 7, 2012

If you are not rebinding the options for the drop down and you are not resetting its actual value on post back, you should not have to do anything with IsPostBack. You should just be able to do the following to get the value and text:

string value = txtGender.SelectedValue;
string text = txtGender.SelectedItem.Text;

Note: the actual value of a control will not be available during Page_Init since the page has not been completely initialized yet.