我正在尝试从数据库向Windows窗体组合框添加项目,以下代码对我有用。代码中引用的表课程有2列,CourseId和CourseName,我想将显示成员设置为CourseName,将值成员设置为CourseId。
请告诉我在下面的代码中我需要做些什么其他更改才能实现这一目标?
private void LoadCourse()
{
SqlConnection conn = new SqlConnection(sasdbConnectionString);
SqlCommand cmd = new SqlCommand("SELECT CourseId FROM Courses", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.courseComboBox.Items.Add(dr.GetInt32(0));
}
dr.Close();
conn.Close();
}
答案 0 :(得分:0)
试试这个..!
private void LoadCourse()
{
SqlConnection conn = new SqlConnection(sasdbConnectionString);
SqlCommand cmd = new SqlCommand("SELECT CourseId,CourseName FROM Courses", conn);
cmd.CommandType = CommandType.Text;
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
this.courseComboBox.DisplayMember =dr[0];
this.courseComboBox.ValueMember = dr[1];
this.courseComboBox.DataSource = dr;
dr.Close();
conn.Close();
}
答案 1 :(得分:0)
尝试使用sql adapter
private void LoadCourse()
{
SqlConnection conn = new SqlConnection(sasdbConnectionString);
string query = "SELECT CourseId,CourseName FROM Courses";
SqlDataAdapter da = new SqlDataAdapter(query, conn);
conn.Open();
DataSet ds = new DataSet();
da.Fill(ds, "Course");
courseComboBox.DisplayMember = "CourseName";
courseComboBox.ValueMember = "CourseId";
courseComboBox.DataSource = ds.Tables["Course"];
}