我知道这是一个愚蠢的问题,但我无法找到如何从我的下拉列表中获取所选值:(
初始化下拉列表:
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;
它没有返回我选择的值,它会在下拉列表出现时保持返回默认值??
有谁能告诉我我做错了什么?谢谢
答案 0 :(得分:5)
您需要确保每次加载页面时都不重新加载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;
答案 1 :(得分:0)
您确定已为要返回的值的选项设置了值吗?
类似这样的事情
<select>
<option value="I am foo">foo</option>
<option value="I am bar">bar</option>
</select>