簡體   English   中英

從下拉列表中獲取選定的值 asp.net

[英]Get selected value from a dropdownlist asp.net

我知道這是一個愚蠢的問題,但我不知道如何從我的下拉列表中獲取選定的值:(

初始化下拉列表:

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

嘗試獲取下拉列表的值:

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

它沒有返回我選擇的值,當下拉列表出現時它一直返回默認值?

誰能告訴我我做錯了什么? 謝謝

您需要確保每次頁面加載時都不會重新加載 DDL,換句話說,僅在初始頁面加載時填充它,如果是頁面回發,則不要重新加載它,因此值將是保留。

像這樣的東西應該工作:

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

}

然后在您的代碼中檢索該值,這應該可以工作:

   string a = TProjectMID.SelectedValue;

你確定你已經為要返回的值的選項設置了一個值嗎?

像這樣的東西

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM