【发布时间】:2015-09-16 07:49:30
【问题描述】:
我有一个 Windows 窗体应用程序。在表单内部,我有一个 ComboBox 和一个列表框。当我选择组合框时,我想显示用户可以在 checkListBox 中检查的项目列表,我想出了如何将数据绑定到组合框部分,但我不确定如何显示列表值,以便用户可以在 checkListBox 中进行选择。假设我有一个存储在 SQL 数据库调用 item_table 中的项目列表,当我从 comboBox 中选择时,如何将其显示到 checkListBox?供参考的代码将不胜感激。谢谢
例如,
假设用户从组合框中选择“Amy”,checkListBox 将显示项目列表“item 1, item2, item3, item4”。
当用户从组合框中选择“Brad”时,它会显示一个项目列表:“item2, item5, item10
等
这是我在 (SQL) 服务器中的数据库表
user_Detail
In my user_Detail table , I have 10 user and each of them have a primary key (userId) and a column (userName);
item_Detail
In my item_Detail table, I have 20 items and they also have a primary key (itemId) and a column (itemName)
在 sql 控制台中,我内部加入了两个表 (我不确定我是否需要在代码中的 SqlCommand 中做同样的事情)
这是我在控制台中的 sql 命令。
select
user_Detail.userId,
user_Detail.userName,
item_Detail.itemId,
item_Detail.itemName
from
item_Detail
INNER JOIN user_Detail ON user_Detail.userId = item_Detail.itemId
这是我的代码
namespace Test {
public partial class MainForm: Form {
SqlConnection myConn;
SqlCommand myCommand;
SqlDataReader myReader;
SqlDataAdapter myDa;
DataTable dt;
DataSet ds = new DataSet();
public MainForm() {
InitializeComponent();
// loadComboBox
loadComboBox();
}
//Connect to my db to fetch the data when the application load
private void loadComboBox() {
myConn = new SqlConnection("Server = localhost; Initial Catalog= dbName; Trusted_Connection = True");
string query = "Select * from user_Detail";
myCommand = new SqlCommand(query, myConn);
try {
myConn.Open();
myReader = myCommand.ExecuteReader();
string s = "<------------- Select an item ----------->";
itemComboBox.Items.Add(s);
itemComboBox.Text = s;
while (myReader.Read()) {
//declare a string
object userId = myReader[userId"];
object userName = myReader["userName"];
//my comboBox named userComboBox
userComboBox.Items.Add(userName.ToString());
}
} catch (Exception ex) {
MessageBox.Show(ex.Message);
}
}
//Display some items here (this is my checkListBox
private item_checkListBox(Object sender, EventArgs e){
}
private void load_item(){
}
【问题讨论】:
标签: c# sql sql-server combobox