Load ComboBox with concatenated string [duplicate]

0

Code that loads comboBox :

private void frmAdicionarProdutos_Load(object sender, EventArgs e)
        {
             this.Load += new System.EventHandler(this.frmAdicionarProdutos_Load);
             string serverName = "localhost";
             string port = "5432";
             string userName = "postgres";
             string password = "adm";
             string databaseName = "GE";
             NpgsqlConnection conn = null;
             string ConnString = null;

             ConnString = String.Format("Server={0};Port={1};User Id={2};Password={3};Database={4};",
                                           serverName, port, userName, password, databaseName);

            using (conn = new NpgsqlConnection(ConnString))
            {
                conn.Open();

                string cmdCarregar = String.Format("SELECT CONCAT(id_produto,' ', nome,' ', preco) FROM PRODUTOS;");
                using (NpgsqlCommand cmd = new NpgsqlCommand(cmdCarregar, conn))
                {
                    NpgsqlDataReader dr = cmd.ExecuteReader();
                    DataTable dt = new DataTable();
                    dt.Load(dr);

                    cbProdutos.DisplayMember = "nome";
                    cbProdutos.ValueMember = "id_produto";
                    cbProdutos.DataSource = dt;
                    conn.Close();
                }     
            }
        }

I set select to concatenate what I need to show in comboBox, but I do not know how to report in DisplayMember . As it is, when I run the program it loads the comboBox with the following value: System.Data.DataRowView .

    
asked by anonymous 24.10.2017 / 14:06

1 answer

2

Come on ... you have to bring the columns in your select, and you do not even need the String.Format:

 string cmdCarregar = "SELECT CONCAT(id_produto,' ', nome,' ', preco) as descricao, id_produto FROM PRODUTOS;";

Notice that I'm mounting a concatenated column, and still bringing the product_id in another column.

using (conn = new NpgsqlConnection(ConnString))
{
    conn.Open();

    string cmdCarregar = "SELECT CONCAT(id_produto,' ', nome,' ', preco) as descricao, id_produto FROM PRODUTOS;";

    using (NpgsqlCommand cmd = new NpgsqlCommand(cmdCarregar, conn))
    {
        NpgsqlDataReader dr = cmd.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);

        cbProdutos.DisplayMember = "descricao";
        cbProdutos.ValueMember = "id_produto";
        cbProdutos.DataSource = dt;
        conn.Close();
    }     
}

Finally, just put in the DisplayMember the name of the column that was created in the query, which was concatenated: descricao

The rest remains the same.

I hope to have helped

    
24.10.2017 / 14:15