简体   繁体   English

选择comboBox项目时显示CheckListBox的项目列表

[英]Display a list of item to CheckListBox when comboBox item is selected

I have a windows form application . 我有一个Windows窗体应用程序 Inside the form, I have a ComboBox and a list box. 在表单内部,我有一个ComboBox和一个列表框。 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. 当我选择comboBox时,我想显示用户可以在checkListBox中检查的项目列表,我想出了如何将数据绑定到comboBox部分,但是我不确定如何显示值列表,以便用户可以在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 ? 假设我有一个存储在SQL数据库中的项目列表,称为item_table,如何根据从comboBox中进行选择的时间将其显示在checkListBox中 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". 假设用户从comboBox中选择“ Amy”,则checkListBox将显示项目“项目1,项目2,项目3,项目4”的列表。

when the user select "Brad" from the comboBox, it will display a list of item: "item2, item5, item10 当用户从comboBox中选择“ Brad”时,它将显示一个项目列表:“ item2,item5,item10

etc 等等

Here is my database table in ( SQL ) server 这是我在( 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) 

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 ) 在sql控制台中,我内部连接了两个表(我不确定是否需要在代码中的SqlCommand中执行相同的操作)

Here is my sql command in the console. 这是我在控制台中的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

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(){




    }

I wish this could help you. 希望对您有所帮助。

First, i just want to fix your loadComboBox() because reading it might lead to confusion. 首先,我只想修复您的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);
        }
    }

Make sure to close sql connections after using it. 使用后请确保关闭sql连接。 Just open it again if youre going to use it. 如果您要使用它,只需再次打开它。

Now, you added the userName of your users on your combobox. 现在,您在组合框中添加了用户的用户名。

Next lets create an event that will be fired whenever you choose from your combobox. 接下来,我们创建一个事件,只要您从组合框中选择,就将触发该事件。

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

The code above can be read as "if userComboBox changed selected index, call ChangeCheckListItems() method." 上面的代码可以读取为“如果userComboBox更改了所选索引,则调用ChangeCheckListItems()方法”。 Whenever you change selection, we will call the said method. 每当您更改选择时,我们都会调用所述方法。 You can put that code on your class constructor. 您可以将代码放在类构造函数上。

Now what does ChangeCheckListItems() method must contain. 现在,ChangeCheckListItems()方法必须包含什么。

private void ChangeCheckListItems(){
    myCheckListBox.Items.Clear();
    string selectedText = userComboBox.Text;

    switch(selectedText){
          case "Amy":
          AddItemsForAmy();
          break;
          case "Brad":
          AddItemsForBrad();
          break:
    }

}

So first, we make sure we clear the myCheckListBox before adding the items to avoid duplication since this method trigger every selection change. 因此,首先,我们确保在添加项目之前清除myCheckListBox以避免重复,因为此方法会触发每次选择更改。

Next we get the selected text from the userComboBox. 接下来,我们从userComboBox中获取选定的文本。

Then we will use a switch to choose what we will do depends on the selected userComboBox. 然后,我们将使用开关选择要执行的操作,具体取决于所选的userComboBox。

AddItemsForAmy() and AddItemsForBrad() are only example methods. AddItemsForAmy()和AddItemsForBrad()只是示例方法。

For example: 例如:

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);
    }
}

So in my example above, I selected all items with itemId that are even numbers. 因此,在上面的示例中,我选择了所有itemId为偶数的项目。 And then on while() part, I added those items to the checklistbox. 然后在while()部分中,我将这些项添加到了清单框。

Its your choice on what items are you going to display for Amy,Brad and other possible users on you database. 您可以选择要为数据库中的Amy,Brad和其他可能的用户显示哪些项目。 You can also use parameterized method for shorter solution. 您也可以使用参数化方法来缩短求解时间。 Hope this helps. 希望这可以帮助。 Sorry if its so long. 很抱歉,如果它这么久。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM