【问题标题】:Display a list of item to CheckListBox when comboBox item is selected选择组合框项目时向 CheckListBox 显示项目列表
【发布时间】: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


    【解决方案1】:

    希望对你有帮助。

    首先,我只想修复您的 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 连接。如果您要使用它,请重新打开它。

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

    接下来让我们创建一个在您从组合框中进行选择时触发的事件。

    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() 部分,我将这些项目添加到了复选框中。

    您可以选择在您的数据库中为 Amy、Brad 和其他可能的用户显示哪些项目。您还可以使用参数化方法来缩短解决方案。希望这可以帮助。抱歉,拖了这么久。

    【讨论】:

    • 嗨贾斯汀,谢谢你的回复,我会试试看。只是想知道,userComboBox.SelectedIndexChanged += (o,ev) =&gt; { ChangeCheckListItems(); }; 代码是在 while 循环之后和 myConn.Close() 之前吗?而且我也明白你为什么要在那里做 swtich 声明,如果组合框中只有 2 个项目,这很好用,但是如果我有 10 个项目,可以说,做所有的 switch 案例会很痛苦吗?我们可以在 foreach 循环中以某种方式循环遍历组合框中的每个项目吗?
    • 您可以将它放在构造函数的 InitializeComponent() 之后。正如我所说,您可以使用参数化方法。就像是。 private void AddItemsToCheckListBox(string userName){ //create a query that will return all items you need for the user. }
    • 谢谢,如果我们不使用开关盒,还有其他方法吗?因为我的组合框中有 10 个或更多项目。这样做会很痛苦:/
    • 您可以使用外键。将外键 fk_userId 添加到 item_Detail 表,并将其引用到 user_Detail 表的 userId。然后您可以使用该外键为用户选择所有项目。您的查询将类似于 select * from item_Detail where fk_userId = userId userId 将是一个方法参数。在这种情况下,您将不再需要开关或循环。
    • 谢谢,我试试看
    猜你喜欢
    • 2011-08-30
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    相关资源
    最近更新 更多