简体   繁体   中英

How to get data from selected item in ListBox and display to checkedBoxList?

在此处输入图片说明 I am working on Windows Form Application. On the Form, i have placed one ListBox and on another tab there is CheckBoxList. I have populated my ListBox with my SQL Datasource. Now, i want to display the list items of each selected item in ListBox and show it to CheckBoxList. 在此处输入图片说明

Use the ListBox.SelectedValueChanged event (or SelectedIndexChanged). Then use the ListBox.SelectedValue property to filter the CheckBoxList Items.

The method for filtering the CheckBoxList depends on how the items are bound. If they are from a database, then I would use SQL to filter the list. (inside the SelectedValueChanged event)

If you post the code that you have tried, I can try to walk you through it.

Edit: Your select statement is "Select * from Electronics", so it looks like you are storing each category in it's own table. If this is the case, you could do something like this:

string query = null;
switch (listBoxCat.SelectedValue) {
    case "Electronics":
        query = "SELECT * FROM Electronics";
        break;
    case "Woman":
        query = "SELECT * FROM Woman";
        break;
    //case etc, etc
}

namespace JustBuyIt { public partial class Form1 : Form { public Form1() { InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {
        tabControl1.SelectedIndex = tabControl1.SelectedIndex + 1;
    }


    private void listBoxCat_SelectedIndexChanged(object sender, EventArgs e)
    {

        //SQL Data Source
        string datasource = "Data Source=LENOVO-NQ;Initial Catalog=JustBuy;Integrated Security=True";


        //Query
        string query = "SELECT * FROM Electronics";

        //ConnectionString
        SqlConnection myConn = new SqlConnection(datasource);

        //SQL Command
        SqlCommand myComm = new SqlCommand(query, myConn);
        //Data Reader
        SqlDataReader myDataReader;
        try
        {
            myConn.Open();
            myDataReader = myComm.ExecuteReader();

            while (myDataReader.Read())
            {
                string temp = myDataReader.GetString(1);
                checkedListBox1.Items.Add(temp);
            }


        }
        catch (Exception)
        {

            MessageBox.Show("Nothing to show!");
        }


    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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