c# – Fill multiple combobox

Question:

I can fill a combobox with DataTable, but in my case I need to fill 2 combobox and 1 checkedboxlist with data from a MySQL database

//formulário cadastro
private void frmCadastroRecibo_Load(object sender, EventArgs e)
{
    Classes.DBconect con = new Classes.DBconect();
    string sqlc = "SELECT * FROM cliente";
    DataTable dtc = new DataTable();
    MySqlDataReader drc = con.returnDataR(sqlc);
    dtc.Load(drc);
    cmbCliente.DisplayMember = "nome";
    cmbCliente.ValueMember = "id";
    cmbCliente.DataSource = dtc;
}

//classe de ligação aplicação e bd
public MySqlDataReader returnDataR(string querySql)
{
    str_sql = querySql;
    MySqlConnection exec = new MySqlConnection();
    exec = abrirBanco();
    MySqlCommand comando = new MySqlCommand();
    comando.CommandText = str_sql.ToString();
    comando.Connection = exec;
    MySqlDataReader sqlReader = comando.ExecuteReader();
    return sqlReader;
}

How can I do this?

Answer:

A simple example of how to do it. Then you adapt according to your needs.

public bool preencheTipo_Usuario(DropDownList dl)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("select ");
            sb.AppendLine("codtipo, descricao_tipo");
            sb.AppendLine("from tbl_tipo_usuario ");

            SqlConnection conexao = new SqlConnection();
            conexao.ConnectionString = ConfigurationManager.ConnectionStrings["conectDarf"].ConnectionString;
            this.cmd = new SqlCommand(sb.ToString(), conexao);

            try
            {
                conexao.Open();
                cmd.ExecuteNonQuery();

                SqlDataReader dr = cmd.ExecuteReader();

                dl.DataSource = dr;
                dl.DataTextField = "descricao_tipo";
                dl.DataValueField = "codtipo";
                dl.DataBind();

                dl.Items.Insert(0, new ListItem("--- SELECIONE ---", "-1"));
            }
            catch (Exception excecao)
            {
                Erro = excecao.Message;
                return false;
            }
            finally
            {
                conexao.Close();

            }

            return true;
        }
Scroll to Top
AllEscort