1

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

1
  • 2
    well .. are you binding within a if(!IsPostBack) ,if not do so and check out Commented Aug 11, 2011 at 11:20

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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>

1 Comment

Does this make sense, he is binding the fields ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.