我试图在c#.net服务器端创建一个下拉列表......但这不起作用..任何人都知道这里出了什么问题?
string conncetionStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection msSQLConnectoin = new SqlConnection(conncetionStr);
SqlCommand msSQLCommand = msSQLConnectoin.CreateCommand();
msSQLCommand.CommandText = "app_Event_Type_Select";
msSQLConnectoin.Open();
SqlDataReader msDataReader = msSQLCommand.ExecuteReader();
while (msDataReader.Read())
{
dropDown.DataSource = msDataReader["Name"].ToString();
dropDown.DataTextField = msDataReader["Name"].ToString();
dropDown.DataValueField = msDataReader["EventTypeID"].ToString();
dropDown.DataBind();
}
答案 0 :(得分:2)
string conncetionStr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
SqlConnection msSQLConnectoin = new SqlConnection(conncetionStr);
SqlCommand msSQLCommand = msSQLConnectoin.CreateCommand();
msSQLCommand.CommandText = "app_Event_Type_Select";
msSQLConnectoin.Open();
SqlDataReader msDataReader = msSQLCommand.ExecuteReader();
dropDown.DataSource = msDataReader;
dropDown.DataTextField = "Name";
dropDown.DataValueField = "EventTypeID";
dropDown.DataBind();
msSQLConnectoin.Close();
msSQLConnectoin.Dispose();
dropDown.Items.Insert(0, "--Select Name--");
}
将msDataReader["Name"].ToString()
替换为您的数据阅读器名称msDataReader
答案 1 :(得分:1)
示例代码:
protected void Page_Load(object sender, EventArgs e)
{
bindDropdownlist()
}
public void bindDropdownlist()
{
SqlDataAdapter dap = new SqlDataAdapter("select colmn1,colmn2 from table", con);
DataSet ds = new DataSet();
dap.Fill(ds);
DropDownList1.DataSource = ds.Tables[0];
DropDownList1.DataTextField = "colmn1";
DropDownList1.DataValueField = "colmn2";
DropDownList1.DataBind();
DropDownList1.Items.Insert(0, "..select...");
}
答案 2 :(得分:0)
阅读here
应该使用包含控件需要绑定的所有信息的对象来设置DataSource
属性。 DataTextField
和DataValueField
应该是DataSource
对象上实际数据的引用。实现目标的一种简单方法是使用DataTable
和Text
字段准备Value
,然后以这种方式绑定控件:
dropDown.DataSource = dt;
dropDown.DataTextField = "Text";
dropDown.DataValueField = "Value";
dropDown.DataBind();
msdn网站上的Here你会发现同样的情况。
答案 3 :(得分:0)
我相信DataTextField和DataValueField应该是您绑定的属性的字符串表示,请参阅related post:
dropDown.DataSource = msDataReader;
dropDown.DataTextField = "Name";
dropDown.DataValueField = "EventTypeID";