从一个DropDownList asp.net获得价值选择 [英] Get selected value from a dropdownlist asp.net
问题描述
我知道这是一个愚蠢的问题,但我不能找出如何从我的dropdownlist获得选择的值:(
I know this is a silly question but i can't find out how to get the selected value from my dropdownlist :(
初始化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;
它没有回我选择的价值,它使返回默认值时,才出现DropDownList的?
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
推荐答案
您需要确保你没有重新加载DDL每次页面加载,换句话说,不仅填补它的初始页面加载,如果它在一个页面回发,不要再加载它,因此值将被保留。
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.
这样的事情应该工作:
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();
}
}
}
,然后在code检索值,这应该工作:
and then in your code to retrieve the value, this should work:
string a = TProjectMID.SelectedValue;
这篇关于从一个DropDownList asp.net获得价值选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!