,他们也这样做。
我试图将数据获取在下拉列表中,但它不起作用。我不明白有什么问题。
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
语句自动关闭连接并在语句块末尾处置资源。即使语句块由于异常或break
或return
语句。