问题描述
我的组合框..
cbodept和cbocourse
我的数据库表..
tbldepartment [deptcode,dept_desc]
tblcourse [coursecode,course_desc,deptcode]
我想要的是:
1.在表单加载期间:在cbodept中显示所有dept_desc。
2 .cbodept值:我希望dept_desc作为保存到我的数据库的值。
2. cbodept_SelectedIndexChanged:我想在我的cbocourse中加载所有课程。
3. cbocourse值:我想将course_desc作为我的数据库中保存的值。
什么我试过了:
my combobox..
cbodept and cbocourse
my db tables..
tbldepartment[deptcode,dept_desc]
tblcourse[coursecode,course_desc,deptcode]
What i want:
1. During form load : display all dept_desc in cbodept.
2. cbodept value : i want dept_desc as value to be save to my db.
2. cbodept_SelectedIndexChanged : i want to load all courses in my cbocourse.
3. cbocourse value : i want course_desc as the value to be save in my db.
What I have tried:
private void loadDepartment()
{
try
{
SqlConnection cnn = new SqlConnection(cs.constring());
DataSet ds = new DataSet();
string getEmpSQL = "select deptcode from tbldepartment";
SqlDataAdapter sda = new SqlDataAdapter(getEmpSQL, cnn);
sda.Fill(ds);
cbodept.DataSource = ds.Tables[0];
cbodept.DisplayMember = ds.Tables[0].Columns[0].ToString();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void loadCourse()
{
try
{
SqlConnection cnn = new SqlConnection(cs.constring());
DataSet ds = new DataSet();
string getEmpSQL = "select coursecode from tblcourse where department= '" + cbodept.Text + "'";
SqlDataAdapter sda = new SqlDataAdapter(getEmpSQL, cnn);
sda.Fill(ds);
cbocourse.DataSource = ds.Tables[0];
cbocourse.DisplayMember = ds.Tables[0].Columns[0].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void cbodept_SelectedIndexChanged(object sender, EventArgs e)
{
loadCourse();
}
推荐答案
try
{
SqlConnection cnn = new SqlConnection(cs.constring());
DataSet ds = new DataSet();
string getEmpSQL = "select deptcode from tbldepartment";
SqlDataAdapter sda = new SqlDataAdapter(getEmpSQL, cnn);
sda.Fill(ds);
cbodept.DataSource = ds.Tables[0].DefaultView;
cbodept.DisplayMember = ds.Tables[0].Columns["deptcode "].ToString();
cbodept.ValueMember = ds.Tables[0].Columns["deptcode "].ToString();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
private void LoadDepartment()
{
var dt = new DataTable();
var conn = new SqlConnection(connectionString);
var cmd = new SqlCommand("SELECT deptcode FROM tbldepartment",conn);
var da = new SqlDataAdapter(cmd);
dt.Clear();
da.fill(dt);
for(DataRow item in dt.Rows)
{
cbodept.Items.Add(item[0].ToString());
}
}
private void LoadCourse()
{
var dt = new DataTable();
var conn = new SqlConnection(connectionString);
var cmd = new SqlCommand("SELECT coursecode FROM tblcourse WHERE department='"+cbodept.Text+"'",conn);
var da = new SqlDataAdapter(cmd);
dt.Clear();
da.fill(dt);
for(DataRow item in dt.Rows)
{
cbocourse.Items.Add(item[0].ToString());
}
}
private void cbodept_SelectedIndexChanged(object sender, EventArgs e)
{
loadCourse();
}
这篇关于C#combox显示项目和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!