Leave selected specific item ComboBox C # WinForms Visual Studio 2017

1

I'm developing an application that contains a customer registry. In this register there is a ComboBox that lists the cities of the database.

My question is: How do I leave ' setado ' the name of a specific city?

For example, the first city that lists by default is ' ABADIA DE GOIAS ', however I would like the selected city to be ' SAO PAULO ', which is in the middle of my list. How can I do this?

  

Code that lists cities in the ComboBox:

String nomeConexao = LoginInfo.StringConexao;
String string_conn = ConfigurationManager.ConnectionStrings[nomeConexao].ConnectionString;
SqlConnection conn = new SqlConnection(string_conn);

String scom = "SELECT COD, CIDADE FROM CODMUNICIPIO ORDER BY CIDADE";

SqlDataAdapter da = new SqlDataAdapter(scom, conn);

DataTable dtResultado = new DataTable();
dtResultado.Clear();
CbCidade.DataSource = null;
da.Fill(dtResultado);

CbCidade.DataSource = dtResultado;
CbCidade.ValueMember = "COD";
CbCidade.DisplayMember = "CIDADE";
CbCidade.SelectedItem = "";
CbCidade.Refresh();
    
asked by anonymous 04.06.2018 / 02:11

1 answer

2

You can set the SelectedValue property:

CbCidade.SelectedValue = 1; //supondo que 1 seja código de Sao Paulo

or you can set the Text also:

CbCidade.Text = "SAO PAULO";

Although I find it unnecessary to run a new query to get the city code that should be parameterized, you should do so:

String sql2 = "SELECT COD FROM  CODMUNICIPIO WHERE CIDADE = '" + CidadeEmpresa + "'"; 

SqlCommand cmd2 = new SqlCommand(sql2, conn); 
SqlDataReader leitor = cmd2.ExecuteReader();
 if (leitor.HasRows)
 {
      leitor.Read();
      this.CbCidade.SelectedValue = leitor["COD"].ToString();
 }

The Correct , would you store the Company City Code in the variable CidadeEmpresa and not the name of it, then you would just do this:

this.CbCidade.SelectedValue = CidadeEmpresa;

and if you still do not change what is stored in the variable, just do the following:

this.CbCidade.Text = CidadeEmpresa;
    
04.06.2018 / 03:21