Error inserting a "SELECT" item into the Combobox

Asked

Viewed 796 times

0

How do I add an item to the Combobox? The item has to be the first on the list with the text "SELECT":
inserir a descrição da imagem aqui


I’m doing like 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: Cannot modify item collection when Datasource property is set.

inserir a descrição da imagem aqui

 private static DataTable ListarIndicacao()
        {
            try
            {
                DataTable dt = PacienteNegocio.ObterIndicacao();
                return dt;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

This is the method of access to the Bank:

public static DataTable ObterIndicacao()
        {
            try
            {
                OleDbConnection conn = new OleDbConnection(Conexao.obterConexao());
                conn.Open();
                OleDbDataAdapter da = new OleDbDataAdapter("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);
            }
        }
  • put the method code ListarIndicacao

  • Ready put

2 answers

1

When Datasource cannot change the list items, it is not possible. With this code you’ll get it:

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);
        }
    }

1


How are you wearing a DataTable as source, you can add an extra 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;
        }
    }

Utilizing:

AddRowComboBox(this.cmbIndicacao,"[Selecione um item]",0);
  • 1

    Thanks, I just had to make this adaptation to meet (decimal)valor for (int)valor.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.