为什么我的下拉列表显示“ system.data.datarowview”而不是实际值

  • 本文关键字:datarowview data system 列表显示 c#
  • 更新时间 :
  • 英文 :


我试图将数据获取在下拉列表中,但它不起作用。我不明白有什么问题。

string connString = @" Data Source=(LocalDB)v11.0;AttachDbFilename='C:UsersoshriDocumentsStock scores.mdf';Integrated Security=True;Connect Timeout=30";
string queryLecturer = "select name_student from student";
SqlConnection conn = new SqlConnection(connString);
//SqlCommand cmdL = new SqlCommand(queryLecturer, conn);
conn.Open();
//SqlCommand SQLCommand = new SqlCommand();
//cmdL.CommandType = CommandType.Text;
//SQLCommand.CommandText = queryLecturer;
//conn.Close();
SqlDataAdapter adapter = new SqlDataAdapter(queryLecturer, conn);
adapter.Fill(subjects);
DropDownListID.DataSource = subjects;
DropDownListID.DataBind();
DropDownListID.DataBind();  
conn.Close();

您正在将包含DataRowView项目的DataSet分配给您的下拉菜单。您的下拉(是System.Windows.Forms.ComboBox吗?)不够聪明,无法从此DataSet中提取实际值。而是使用SqlDataReader读取字符串值,并将它们添加到可以用作下拉的数据源的列表中。

string connString = @"Data Source=...";
string queryLecturer = "select name_student from student";
using (var conn = new SqlConnection(connString))
using (var cmd = new SqlCommand(queryLecturer)) {
    conn.Open();
    using (SqlDataReader reader = cmd.ExecuteReader()) {
        var list = new List<string>();
        while (reader.Read()) {
            list.Add(reader.GetString(0)); // 0 is the column index.
        }
        DropDownListID.DataSource = list;
    }
}

using语句自动关闭连接并在语句块末尾处置资源。即使语句块由于异常或breakreturn语句。

,他们也这样做。

最新更新