How to return the collection of Items to combobox in c #?

0

Good day, I have a combobox that I load with a data by means of a query from a button (Search), that same combobox has a data collection (15 items from the properties) when I open the form the first time, but after loading it from the database , after cleaning it, the data collection no longer appears, only the data that loads from the database appears in the collection.
I clean it like this:

cmb.SelectedIndex = -1  

This if you clean my combobox but I want to return the complete collection as when I executed it the first time.
I want to do as a refresh or something that recharges my combobox like the princio ...
How would you do it in that case?

Additional information: This is how I charge the combobox:

SqlCommand micommand= new SqlCommand(querySQL,conexion);

        SqlDataReader BuscaRead;
        conexion.Open();
        BuscaRead = micommand.ExecuteReader();
       //si trae datos los consulta le paso el dato al combo directamente, no utilizo datasource ya que solo devuelbe un dato
        if (BuscaRead.Read())
        {
combo.Items.Add(BuscaRead["campo"].ToString());
        }

When I pass the data to the combobox and then use a button called "cancel" that clears other fields and I also want to clean the combo and return the list that I assign from properties, but does not return that list, it only appears the field that is added from the database. How can you return the collection of data that you had from the beginning?

    
asked by Manny 10.10.2018 в 22:15
source

1 answer

0

To assign data to the combo, use an entity and not the Items.Add (), such as

conexion.Open();
SqlCommand micommand= new SqlCommand(querySQL,conexion);

SqlDataReader BuscaRead = micommand.ExecuteReader();

List<Item> lista = new List<Item>();
if (BuscaRead.Read())
{
    var item = new Item() 
    { 
        campo = Cnvert.ToString(BuscaRead["campo"])
    };

    lista.Add(item);
}

combo.ValueMember = "campo";
combo.DisplayMember = "campo";
combo.DataSource = lista;

For this he defines a class

public Item{
   public string campo {get;set;}
}

in this case you only indicate a field, then in the code you can do

combo.SelectedValue = val;

where "val" is a value that exists in the field

    
answered by 11.10.2018 в 23:45