Get selected value from a dropdownlist asp.net

后端 未结 2 1500
一整个雨季
一整个雨季 2021-01-25 02:17

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:

             SqlComman         


        
相关标签:
2条回答
  • 2021-01-25 02:23

    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;
    
    0 讨论(0)
  • 2021-01-25 02:41

    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>
    
    0 讨论(0)
提交回复
热议问题