当选择组合框项时,将项列表显示到CheckListBox

本文关键字:列表显示 CheckListBox 选择 组合 | 更新日期: 2023-09-27 18:13:07

我有一个windows窗体应用程序在表单中,我有一个组合框和一个列表框。当我选择comboBox时,我想显示用户可以在checkListBox中检查的项目列表,我弄清楚了如何将数据绑定到comboBox部分,但我不确定如何显示值列表,以便用户可以在checkListBox中进行选择。假设我有一个项目列表,存储在一个SQL数据库调用item_table,我怎么能显示它到checkListBox根据当我从comboBox选择?代码供参考将不胜感激。由于

例如

假设用户从组合框中选择"Amy",则checkListBox将显示一个项目列表"item1, 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(){


    }

当选择组合框项时,将项列表显示到CheckListBox

我希望这对你有帮助。

首先,我只是想修复你的loadComboBox(),因为读取它可能会导致混乱。

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
                string userId = myReader["userId"].toString();
                string userName = myReader["userName"].toString();
                //my comboBox named userComboBox
                userComboBox.Items.Add(userName);
            }
            myConn.Close();
        } catch (Exception ex) {
            MessageBox.Show(ex.Message);
        }
    }

确保在使用后关闭sql连接。如果你要用的话,再打开一遍。

现在,您在组合框中添加了用户的userName。

接下来,让我们创建一个事件,当你从组合框中选择时,它将被触发。

userComboBox.SelectedIndexChanged += (o,ev) => { ChangeCheckListItems(); };

上面的代码可以理解为"如果userComboBox改变了选择的索引,调用ChangeCheckListItems()方法。"无论何时更改选择,我们都将调用上述方法。你可以把这些代码放在你的类构造函数中。

现在ChangeCheckListItems()方法必须包含什么?

private void ChangeCheckListItems(){
    myCheckListBox.Items.Clear();
    string selectedText = userComboBox.Text;
    switch(selectedText){
          case "Amy":
          AddItemsForAmy();
          break;
          case "Brad":
          AddItemsForBrad();
          break:
    }
}

因此,首先,我们确保在添加项目之前清除myCheckListBox以避免重复,因为该方法触发每次选择更改。

接下来我们从userComboBox中获得选中的文本。

然后我们将使用一个开关来选择我们将做什么取决于所选择的userComboBox

AddItemsForAmy()和AddItemsForBrad()只是示例方法。

例如:

private void AddItemsForAmy(){
    myConn = new SqlConnection("Server = localhost; Initial Catalog=dbName         Trusted_Connection=true;"
    string query = "Select * from item_Detail where itemId % 2 = 0"
    myCommand = new SqlCommand(query, myConn);
    try{
      myConn.Open();
      myReader = myCommand.ExecuteReader();
      while(myReader.Read()){
      string itemName = myReader["itemName"].toString();
      myCheckListBox.Items.Add(itemName);
      }
      myConn.Close();
    }
    catch(SqlExcetion ex){
           MessageBox.Show(ex.Message);
    }
}

所以在上面的例子中,我选择了itemId为偶数的所有项目。然后在while()部分,我将这些项添加到checklistbox中。

你可以选择在数据库中为Amy、Brad和其他可能的用户显示哪些项目。您还可以使用参数化方法来缩短求解时间。希望这对你有所帮助。不好意思,太长了