0

我尝试在 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();

    }
4

4 回答 4

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

于 2012-08-04T05:04:48.950 回答
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...");
    }
于 2012-08-04T07:01:37.193 回答
0

在这里阅读 该DataSource属性应该使用包含控件需要绑定到的所有信息的对象进行设置。和应该是对对象实际数据的DataTextField引用。实现目标的一种简单方法是准备一个using和字段,然后以这种方式绑定控件:DataValueFieldDataSourceDataTableTextValue

dropDown.DataSource = dt;
dropDown.DataTextField = "Text";
dropDown.DataValueField = "Value";
dropDown.DataBind();

在msdn 网站上,您会找到相同的场景

于 2012-08-04T05:04:57.077 回答
0

我相信 DataTextField 和 DataValueField 应该是您绑定的属性的字符串表示形式,请参阅此相关帖子

 dropDown.DataSource = msDataReader;
 dropDown.DataTextField = "Name";
 dropDown.DataValueField = "EventTypeID";
于 2012-08-04T05:05:25.173 回答