我有一个SQL数据库表,有两列; ' ID'和'姓名'。 我想从数据库中读取这些数据并将其添加到ListBox中,并使用' Name'作为新的项目文本字段和' ID'作为价值领域。
这是我到目前为止所做的:
using (SqlConnection conn = new SqlConnection("ConnectionString)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM Buildings", conn)) {
using (SqlDataReader reader = cmd.ExecuteReader()) {
while (reader.Read()) {
for (int i = 0; i < reader.FieldCount; i++) {
........................
}
}
}
任何帮助都将不胜感激。
答案 0 :(得分:0)
你可以试试这个:
SqlConnection conn = new SqlConnection("Your Connection String");
SqlCommand cmd = new SqlCommand("Your SQL Query", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
ListView1.DataSource = dt;
ListView1.DataBind();
答案 1 :(得分:0)
结束工作
int selectedBuilding = int.Parse(listBox1.GetItemText(listBox1.SelectedValue));
using (SqlConnection conn = new SqlConnection("ConnectionStrin")) {
using (SqlCommand cmd = new SqlCommand("SELECT ID, Name FROM Printers WHERE BuildingID = " + selectedBuilding + "", conn)) {
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
conn.Close();
listBox2.DataSource = dt;
listBox2.ValueMember = "ID";
listBox2.DisplayMember = "Name";
}
}
谢谢你的帮助!