Store the info of a combox in a variable in C #

1

I'm just beginning on the subject of programming, and I want to ask for your help; I have a drawback and I can not find how to store the values of a combobox in C # in a variable.

I have a combobox that I have called CmbMes. in this store the numbers of the month (1,2,3 ... 12).

At the time of going to the part of the code I have a variable variable of type int and that's where I want to store the combo but I get an error.

I tried with month = CmbMes.text; , with month = CmbMes.SelectedValue; , and a couple more and it does not work for me.

Thanks for the help

    
asked by CRISTIAN SANCHEZ 30.03.2018 в 03:17
source

2 answers

0

I do not know how you are filling your ComboBox but here I show you an example of how you could do it.

private void llenarComboMeses(ComboBox combo)
{
     List<string> lista_meses = new List<string>();
     lista_meses.Add("Enero");
     lista_meses.Add("Febrero");
     lista_meses.Add("Marzo");
     lista_meses.Add("Abril");
     lista_meses.Add("Mayo");
     lista_meses.Add("Junio");
     lista_meses.Add("Julio");
     lista_meses.Add("Agosto");
     lista_meses.Add("Septiembre");
     lista_meses.Add("Octubre");
     lista_meses.Add("Noviembre");
     lista_meses.Add("Diciembre");

     //Limbiar los datos del combo, para no duplicarlos al volver a generarlos
     combo.DataSource = null;
     combo.Items.Clear();

     //Recorrer la lista y asignar los valores al combo
     foreach (string mes in lista_meses)
     {
        //Asignando los valores.
        combo.Items.Add(mes);
     } 
 }

To use the function like this:

llenarComboMeses(CmbMes);

Then to get the value of the selected month you can do it in the event SelectedIndexChanged of your ComboBox like this:

private void CmbMes_SelectedIndexChanged(object sender, EventArgs e)
{
     if (CmbMes.SelectedIndex >= 0)
     {
        //Asignar el valor a tu variable.
        mes =  CmbMes.SelectedIndex + 1;
     }
}
  

This is done: CmbMes.SelectedIndex + 1; adding 1 because the index starts at zero therefore when adding one the index 1 will be equal to Enero , then index 2 = Febrero , etc ...

    
answered by 02.04.2018 в 15:13
0

The problem is that the properties to obtain the selected value of the combobox is of type Object or String and your variable is whole, so you have to convert it.

Example:

int n = int.Parse(comboBox1.Text);
//o
int n = int.Parse(comboBox1.SelectedItem);
    
answered by 02.04.2018 в 15:22