Display a list of item to CheckListBox when comboBox item is selected

时间:2015-09-16 07:49:31

标签: c# sql sql-server combobox

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




    }

1 个答案:

答案 0 :(得分: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连接。如果要使用它,请再次打开它。

现在,您在组合框中添加了用户的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和您数据库上的其他可能用户显示哪些项目。您还可以使用参数化方法来缩短解决方案。希望这可以帮助。对不起,如果这么久。