List items other than the database in the Combobox in C # winforms

0

I have a C # application that performs a search. For this is used a field called 'status' that nothing else a list in a combobox. I need it to appear in addition to the statuses that come from the bank, a status called 'ALL' that does not exist in the bank, and if possible that it comes first in the combobox at the time of listing. Follow my code to list the fields.

String string_conn = ConfigurationManager.ConnectionStrings["conexao"].ConnectionString;
NpgsqlConnection conn = new NpgsqlConnection(string_conn);
      try
          {
            conn.Open();
           }
           catch (NpgsqlException sqle)
          {
              MessageBox.Show("Falha ao efetuar a conexão. Erro: " + sqle);
           }
                String sql = "SELECT * FROM usuario";
                NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
                DataTable dtResultado = new DataTable();
                dtResultado.Clear();
                da.Fill(dtResultado);

                Invoke((MethodInvoker)delegate
                {
                    CbUsuario.DataSource = null;
                    CbUsuario.DataSource = dtResultado;
                    CbUsuario.ValueMember = "cod";
                    CbUsuario.DisplayMember = "nome";
                    CbUsuario.SelectedItem = "";
                    CbUsuario.Refresh();
                });
                conn.Close();
    
asked by anonymous 04.07.2018 / 03:36

1 answer

2

Based on this response from the OS it is not possible to directly add a new item in the combobox that is filled in through the DataSource , to do this you have to add the item in the object being binding , in your case, add in DataTable , your code would be more or less like this:

String string_conn = ConfigurationManager.ConnectionStrings["conexao"].ConnectionString;
NpgsqlConnection conn = new NpgsqlConnection(string_conn);
try
{
  conn.Open();
}
catch (NpgsqlException sqle)
{
    MessageBox.Show("Falha ao efetuar a conexão. Erro: " + sqle);
}
String sql = "SELECT * FROM usuario";
NpgsqlDataAdapter da = new NpgsqlDataAdapter(sql, conn);
DataTable dtResultado = new DataTable();
dtResultado.Clear();
da.Fill(dtResultado);

//Adiciona uma linha com código 0 e texto "todos"
dtResultado.Rows.Add("0", "TODOS");

//Ordena por id o datatable
DataView view = dtResultado.DefaultView;
view.Sort = "cod ASC";
DataTable dtSorted = view.ToTable();

Invoke((MethodInvoker)delegate
{
    CbUsuario.DataSource = null;
    CbUsuario.DataSource = dtResultado;
    CbUsuario.ValueMember = "cod";
    CbUsuario.DisplayMember = "nome";
    CbUsuario.SelectedItem = "";
    CbUsuario.Refresh();
});
conn.Close();

In order for "ALL" to appear first, an order was placed through the cod column of DataTable

    
04.07.2018 / 04:49