0

How can I set the first line of Combobox empty in my code? This is the function that is called when the form loads and it inserts the options on the Combobox.

private void preencherComboDpt()
        { carregandoComboDepartamentos = true;

            NpgsqlConnection conn = new NpgsqlConnection();
            try
            {
                conn = new NpgsqlConnection(connstring);                
                string query = "select * from departamento order by departamento";
                NpgsqlCommand cmd = new NpgsqlCommand(query, conn);                
                cmd.CommandText = query;
                conn.Open();
                NpgsqlDataReader drd = cmd.ExecuteReader();
                DataTable dt = new DataTable("tabela");

                dt.Columns.Add("departamento_id", typeof(int));
                dt.Columns.Add("departamento", typeof(string));

                while (drd.Read())
                {

                    DataRow row = dt.NewRow();                    
                    row["departamento_id"] = int.Parse(drd["departamento_id"].ToString());
                    row["departamento"] = drd["departamento"].ToString();
                    dt.Rows.Add(row);                  


                }

                cobUnivDep.DataSource = dt.DefaultView;
                cobUnivDep.DisplayMember = "departamento";
                cobUnivDep.ValueMember = "departamento_id";  


            }
            catch
            {
                MessageBox.Show("Error ");
            }
            carregandoComboDepartamentos = false;

        }

I already tried inserting the line cobUnivDep.SelectedIndex = null, but it doesn't work.

  • try setting cobUnivDep.Selecteditem=null – user8276908 May 28 '20 at 18:42
  • 1
    `dt.Rows.InsertAt(dt.NewRow(), 0);`. Btw, you can load your DataTable simply with `dt.Load(drd)` (you don't need to add Columns and iterate `DataReader.Read()`). Then, set the `DisplayMember` and `ValueMember` properties before you set the DataSource. – Jimi May 28 '20 at 18:44
  • Thank you so much. @Jimi It's working :) – Sara Raquel May 28 '20 at 19:04
  • @Jimi do you know how to show "Select an item" on the combo box? – Sara Raquel May 28 '20 at 19:22
  • If you want to show the `Select an item...` thing, then you probably want a `CueBanner` instead of an empty item. See here: [ComboBox Cue Banner not italic when DropDownStyle is DropDown](https://stackoverflow.com/a/8904184/7444103), for example. Or here: [Set hint or watermark or default text for ComboBox without adding it as item](https://stackoverflow.com/a/50972125/7444103). – Jimi May 28 '20 at 19:41
  • ...or the extension method (the c# version, just edited) [here](https://stackoverflow.com/a/59803179/7444103), so you can just write `comboBox1.SetCueBanner("Select an item...")` – Jimi May 28 '20 at 21:07

0 Answers0