How to pass selected items from a checkedlistbox to a listbox with C #?

0

Hello everyone, first of all thank you for taking the time to read me. I am doing program using visual studio 15 community programming from C #. In the program I connect to a database made in SQL Server 2008 from which I obtain keys for some products that are for sale. The above I do from a class called "connection" to which I pass all the corresponding parameters and load the results of the query in a checkedlistbox in order that the user can select the products you want. The selected objects are passed (or at least that is what I should do) to a listbox so that I can only see the selected ones but it does not, I do not know if someone can tell me what I'm doing wrong or guide me please. Thanks in advance.

    class conexion{
      public void claves_semanas(CheckedListBox clb)
    {
        try
        {
            DataTable dt = new DataTable();
            using (SqlConnection conn = new SqlConnection("Data Source=Server;Initial Catalog=Productos;Persist Security Info=True;User ID=creedence;Password=fortunateson"))
            {
                string query = "select DS_productos FROM tiend.C_productos WHERE FE_INICIO > '2016-01-10' ORDER BY FE_INICIO";   //aqui omiti los datos por razones de que no puedo dar la información de los productos el caso es que necesito ver los productos que se dieron de alta desde el 2016-01-10
                SqlCommand buscador = new SqlCommand(query, conn);
                SqlDataAdapter da = new SqlDataAdapter(buscador);
                da.Fill(dt);
                clb.DisplayMember = "DS_productos";
                clb.DataSource = dt;
            }
        }

        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex.ToString());
        }
    }

}

Until then the code I use for the connection ends, now this is the code I use in the main

     foreach (var s in checkedListBox1.CheckedItems)
        {
            listBox1.Items.Add(s.ToString());
        }

Obviously marks error, although I do not know because sincerely. UPDATE.

The error it gives is this in the listbox: System.Data.DataRowView That's the only thing you can appreciate.

Also try using the 'ItemCheck' event in this way

       private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        string item = checkedListBox1.SelectedItem.ToString();
        if (e.NewValue == CheckState.Checked)
            listBox1.Items.Add(item);
        else
            listBox1.Items.Remove(item);
    }

To which only the word 'collection' is returned to me in listbox, I do not know why this happens because my knowledge is quite basic and even though I searched for documentation on the MSDN, I did not find anything that could help me.

I also have to clarify that before using all the code that I put before I used this code in my class:

      public void claves_semanas(CheckedListBox clb)
    {
        int stop = 1;
     dr8 = cmd8.ExecuteReader();
                while (stop > 0)
                {
                    while (dr8.Read())
                    {
                        clb.Items.Add(dr8["DS_SEMANA"].ToString());
                    }
                    clb.SelectedIndex = 0;
                    dr8.Close();
                    stop = -1;
                }
          }

and in the main I used this

       foreach (string s in checkedListBox1.CheckedItems)
        {
           listBox1.Items.Add(s);
        }

And it worked fine except for one detail, which is that the data came back to me twice, I thought I had solved it in the class with the stop variable, to make the cycle only be done once, but it never turned out, which led me to use the code I put up, with that code if I managed to show the data only once, although I can not make them appear in the listbox.

I hope and you can help me. Greetings

    
asked by user7070220 19.01.2017 в 20:35
source

2 answers

1

Declare in your class:

    private BindingList<string> DatosCheckBox = new BindingList<string>();
    private BindingList<string> DatosLista = new BindingList<string>();

Now in your practice

 public void claves_semanas(CheckedListBox clb)
{
    try
    {
        using (SqlConnection conn = new SqlConnection("Data Source=Server;Initial Catalog=Productos;Persist Security Info=True;User ID=creedence;Password=fortunateson"))
        {
            string query = "select DS_productos FROM tiend.C_productos WHERE FE_INICIO > '2016-01-10' ORDER BY FE_INICIO";   //aqui omiti los datos por razones de que no puedo dar la información de los productos el caso es que necesito ver los productos que se dieron de alta desde el 2016-01-10
            SqlCommand buscador = new SqlCommand(query, conn);
            conn.Open();
            var rdr = buscador.ExecuteReader();
            while (rdr.Read())
            {
                DatosCheckBox.Add(rdr["DS_productos"].ToString());
            }
            checkedListBox1.DataSource = DatosCheckBox;
            listBox1.DataSource = DatosLista;
            conn.Close();
        }
    }

    catch (Exception ex)
    {
        MessageBox.Show("Error" + ex.ToString());
    }
}

In the event of your CheckedListBox:

private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
    {
        var index = e.Index;
        var listbox = sender as CheckedListBox;
        var item = DatosCheckBox.Where(W => W == listbox.Items[index].ToString()).Single();

        switch (e.CurrentValue)
        {
            case CheckState.Unchecked:
                DatosLista.Add(item);
                break;
            case CheckState.Checked:
                DatosLista.Remove(item);
                break;
            default:
                break;
        }
    }

Note: if your database object is a composite type you will need to substitute BindingList for the type you use

    
answered by 19.01.2017 в 22:09
0

Hello, I have solved the problem through the link that @Mauricio put

I leave the way I did it in case someone comes to serve in the future.

The only thing I had to do was modify the main in this way:

     private void agregarSemanasToolStripMenuItem_Click(object sender, EventArgs e)

    {
        string s = "";

        foreach (DataRowView drv in checkedListBox1.CheckedItems)
        {
            s += drv[0].ToString() + ",";
        }
        s = s.TrimEnd(',');
        listBox1.Items.Add(s);
    }

And with that I managed to obtain the desired result. Thanks to both for helping me.

Greetings

    
answered by 20.01.2017 в 20:20