I have a windows form application. Inside the form, I have a ComboBox and a list box. When I select the comboBox, I want to display a list of item that the user can check in the checkListBox, I figured out how to bind data to comboBox part but I am not sure how to display a list of values so that the user can select in the checkListBox. Let say I have a list of items that stored in a SQL database call item_table, how can I display it to the checkListBox according to when I select from the comboBox? Code for reference will be appreciated. Thanks
For example,
let say the user select "Amy" from the comboBox, the checkListBox will display a list of item "item 1, item2, item3, item4".
when the user select "Brad" from the comboBox, it will display a list of item: "item2, item5, item10
etc
Here is my database table in (SQL) server
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)
In the sql console, I inner join the two table (which I am not sure if I need to do the same in my SqlCommand in the code )
Here is my sql command in the console.
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
Here is my code
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(){
}