Get selected value from a dropdownlist asp.net

I know this is a silly question but i can’t find out how to get the selected value from my dropdownlist 🙁

Init the dropdownlist:

             SqlCommand command = new SqlCommand("SelectAllUserID", connection);
             command.CommandType = CommandType.StoredProcedure;

            SqlDataReader sqlReader = command.ExecuteReader();
            if (sqlReader.HasRows)
            {
                TProjectMID.DataSource = sqlReader;
                TProjectMID.DataTextField = "UserID";
                TProjectMID.DataValueField = "UserID";
                TProjectMID.DataBind();
            }

Try to get the value of drop down list:

                String a;
                a = TProjectMID.SelectedValue;
                a = TProjectMID.SelectedItem.Value;
                a = TProjectMID.DataValueField;
                a = TProjectMID.Text;

It didn’t return the value I chose, it keeps returning the default value when the dropdownlist appear ??

Can anybody tell me what I did wrong ? Thank you

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You need to make sure you are not re-loading the DDL everytime the page loads, in other words only fill it on the initial page load, and if it is a page postback, don’t re-load it so the value will be retained.

Something like this should work:

   protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack) {

         SqlCommand command = new SqlCommand("SelectAllUserID", connection);
         command.CommandType = CommandType.StoredProcedure;

          SqlDataReader sqlReader = command.ExecuteReader();
          if (sqlReader.HasRows)
          {
            TProjectMID.DataSource = sqlReader;
            TProjectMID.DataTextField = "UserID";
            TProjectMID.DataValueField = "UserID";
            TProjectMID.DataBind();
          }
        }

}

and then in your code to retrieve the value, this should work:

   string a = TProjectMID.SelectedValue;

Method 2

have you made sure that you have set a value on the options for the value to be returned?

something like this

<select>
<option value="I am foo">foo</option>
<option value="I am bar">bar</option>
</select>


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x