Bank query for a List in C # WPF

3

I need to make a query in the database, I made this code for connection, but I do not know how to proceed to put this information in a list<String>

SqlConnection conexao = new SqlConnection(_stringConexao);
SqlCommand comando = new SqlCommand("SELECT CodEstabelecimento 
                                     FROM TBEstabelecimentos", conexao);

List<String> teste = new List<string>();

I want to use list as the basis for combobox , I do not know if this is a good practice, if you have another more practical way I accept it too.

Note: I'm connecting to a bank SQLServer

    
asked by anonymous 22.12.2014 / 11:57

1 answer

2

If you just want to generate the list and turn around then one way to do this would be like this:

public IEnumerable<string> PegaLista() {
    //cria a conexão garantindo que ela será fechada. A string é pega do arquivo de configuração
    //É possível a string de conexão pegar da fonte que você quiser
    using (var connection = new SqlConnection(Properties.Settings.Default.DBConnectionString))
    //cria uma *query* garantindo que ela será encerrada ao final
    using (var cmd = connection.CreateCommand()) {
        connection.Open(); //abre conexão
        cmd.CommandText = "select COUNT(CodEstabelecimento) as contagem from TBEstabelecimentos"; //define a query p/ o DB
        using (var reader = cmd.ExecuteReader()) { //cria um leitor do ADO.Net
            while (reader.Read()) { //vai lendo cada item do resultado do select
                //retorna sob demanda cada item encontrado
                yield return reader.GetString(reader.GetOrdinal("contagem"));
            }
        }
    }
}

If you need to generate the concrete list you can do:

var teste = PegaLista();

You do not need to generate the concrete list, you can get the data directly through a binding getting efficiency.

Read another answer to understanding yield .

If you prefer to generate the list in the traditional way you can do:

public List<string> PegaLista() {
    var lista = new List<string>();
    //cria a conexão garantindo que ela será fechada. A string é pega do arquivo de configuração
    //É possível a string de conexão pegar da fonte que você quiser
    using (var connection = new SqlConnection(Properties.Settings.Default.DBConnectionString))
    //cria uma *query* garantindo que ela será encerrada ao final
    using (var cmd = connection.CreateCommand()) {
        connection.Open(); //abre conexão
        cmd.CommandText = "select COUNT(CodEstabelecimento) as contagem from TBEstabelecimentos"; //define a query p/ o DB
        using (var reader = cmd.ExecuteReader()) { //cria um leitor do ADO.Net
            while (reader.Read()) { //vai lendo cada item do resultado do select
                //adiciona cada item encontrado na lista que será retornada
                lista.Add(reader.GetString(reader.GetOrdinal("contagem")));
            }
        }
    }
    return lista;
}

Calling the method:

var teste = PegaLista();

Something tells me that you do not want to use COUNT() in this query , it will produce a unique result, not an effective list. But then you evaluate and trade for a suitable field.

With this list you will still have to create a binding with WPF. There are several ways to do this and the best depends on the desired result.

In that answer in the SO has a more complete example to do binding . It is not showing how to fetch from the database but shows how CollectionView can be populated with a generated list as I've shown above.

Using WPF is not something simple, you need to fully understand how it works. You can not go trying to do something on the basis of "my boo boo" as it does with other technologies. Well, even give it to you will do everything wrong and will learn to do everything crooked. The best way to learn to use this technology is by following a good book (which I know only exists in English) that details every aspect well. Fragmented knowledge in this case will do more harm than good.

This is still a naive way of creating a WPF application. A real application will require more effort.

small tutorial .

    
22.12.2014 / 14:03