Error inserting a "SELECT" item in the Combobox

0

How do I add an item in the Combobox? The item has to be first in the list with the text "SELECT":


I'm doing this:

private void PreencherCmbIndicacao()
        {
            try
            {
                this.cmbIndicacao.Items.Clear();
                this.cmbIndicacao.DataSource = ListarIndicacao();
                this.cmbIndicacao.ValueMember = "IDPACIENTE";
                this.cmbIndicacao.DisplayMember = "NOME";   
                this.cmbIndicacao.Items.Insert(0, "SELECIONE");
                //this.cmbIndicacao.Text = "SELECIONE";
            }
            catch (Exception e)
            {
                throw new Exception("Erro ao listar Indicação do Paciente: " + e.Message);
            }
        }

And this error occurs: Can not modify collection of items when DataSource property is set.

privatestaticDataTableListarIndicacao(){try{DataTabledt=PacienteNegocio.ObterIndicacao();returndt;}catch(Exceptionex){thrownewException(ex.Message);}}

ThisisthemethodofaccessingtheBank:

publicstaticDataTableObterIndicacao(){try{OleDbConnectionconn=newOleDbConnection(Conexao.obterConexao());conn.Open();OleDbDataAdapterda=newOleDbDataAdapter("Select IDPACIENTE, NOME From TBPaciente WHERE NOME IS NOT NULL ORDER BY NOME", conn);
                DataTable dt = new DataTable();
                da.Fill(dt);
                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception("Erro ao listar dados de Indicação: " + ex.Message);
            }
        }
    
asked by anonymous 04.03.2018 / 23:36

2 answers

2

Since you are using DataTable as source, you can add one more line with the text and value you want. If you were using a list, it would be more complicated.

  

I use this method:

    public static void AddRowComboBox(ComboBox cb, string texto, object valor)
    {
        if (cb.DataSource is DataTable)
        {
            DataTable dt = (DataTable)cb.DataSource;
            DataRow r = dt.NewRow();

            if (valor == null)
                r[cb.ValueMember] = DBNull.Value;
            else if (dt.Columns[cb.ValueMember].DataType == typeof(int) || dt.Columns[cb.ValueMember].DataType == typeof(long) || dt.Columns[cb.ValueMember].DataType == typeof(decimal))
                r[cb.ValueMember] = (decimal)valor;
            else if (dt.Columns[cb.ValueMember].DataType == typeof(string))
                r[cb.ValueMember] = valor;

            r[cb.DisplayMember] = texto;

            dt.Rows.InsertAt(r, 0);
            cb.DataSource = dt;
        }
    }
  

Usage:

AddRowComboBox(this.cmbIndicacao,"[Selecione um item]",0);
    
05.03.2018 / 01:16
2

When using the DataSource you can not change the items in the list, it is not possible. With this code you will achieve this:

private void PreencherCmbIndicacao()
    {
        try
        {
            string connectionString = @"Password=sasa;Persist Security Info=True;User ID=sa;Initial Catalog=DEMO;Data Source=.";

            string query = "SELECT Nome, NumContrib FROM clientes";

            SqlConnection con = new SqlConnection(connectionString);

            SqlDataAdapter da = new SqlDataAdapter(query, con);

            SqlCommandBuilder cb = new SqlCommandBuilder(da);
            DataSet ds = new DataSet();
            da.Fill(ds);

            cmbIndicacao.Text = "-SELECIONE-";
            foreach (DataRow dr1 in ds.Tables[0].Rows)
            {
                cmbIndicacao.Items.Add(dr1["Nome"].ToString());
            }


            //this.cmbIndicacao.Items.Insert(0, "SELECIONE");
            //this.cmbIndicacao.Text = "SELECIONE";
        }
        catch (Exception e)
        {
            throw new Exception("Erro ao listar Indicação do Paciente: " + e.Message);
        }
    }
    
05.03.2018 / 01:00