Correct method to get Datatable populated Combobox value

Asked

Viewed 5,127 times

1

What is the right way to get the value of a ComboBox populated by a DataTable?

I’m using the following code:

private void ComboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
    Consulta_cidade cidade = new Consulta_cidade();

    var dataRowView = this.comboBox3.SelectedItem as DataRowView;
    var valor = dataRowView.Row.ItemArray[1];

    int a = Convert.ToInt32(valor);

    comboBox2.DataSource = cidade.consulta_cidade(a);
    comboBox2.ValueMember = "descricao";
    comboBox2.DisplayMember = "descricao";
    comboBox2.Update();
}
  • 1

    You can use the property SelectedItem to take the display value and property SelectedValue to take the code associated with the Display value.

  • Dener, this method, cannot be applied here, because when we use a datatable to popular a combobox, the values return as object, not as string. That’s why I needed to use a Datarowview. Correct me if I’m wrong. Thank you

  • 1

    It’s WPF or Winforms?

  • Dener I’m working with Winforms

  • 1

    Where the value is returned as an object?

  • 1

    Just convert to whole: int valor = Convert.ToInt32(comboBox3.SelectedValue);

  • Dener, perfect, I redid the code as you said. and solved the problem. I do not know pq, yesterday was not getting. I could not identify the error. Thank you.

  • @Denercarvalho Post this as an answer.

  • @zekk yes I will post

Show 4 more comments

1 answer

3


Just make the conversion to whole using the method ToInt32() see:

int valor = Convert.ToInt32(comboBox3.SelectedValue);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.