How to load data into a combobox whenever registering new values

Asked

Viewed 291 times

1

How do I make sure that each course registration is automatically updated the course combobox without having to close and open the application again? Ex: I register a course "Administration" and load this course in the combobox. Follow the code to insert the data in the combobox

private void ConfigCursoUC_Load(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=LAPTOP-EVMCT3AM;Initial Catalog=dbESCOLA;Integrated Security=True";
        con.Open();
        SqlCommand sql = new SqlCommand();
        sql.Connection = con;
        sql.CommandText = "SELECT NomeCurso FROM tbCURSO";
        SqlDataReader dr = sql.ExecuteReader();
        DataTable tb = new DataTable();
        tb.Load(dr);

        cmbCurso.DisplayMember = "NomeCurso";
        cmbCurso.DataSource = tb;

    }

Tela de cadastro de cursos e matérias

  • Bruno the simple answer to the question would be to use Ajax to make asynchronous requests to the server and collect the new courses or simply by adding a new course make a.add item in the course name combobox when the user clicks to register, but your question lacked details so that we can fully understand your problem, what technology are you using next to C# ? Forms, Web ... And if possible post your code on github or somewhere else so we can download it and try to give you a light

1 answer

1


You can do something like this:

// colocar a ConnectionString como variável global ao Form
private string connString = "Data Source=LAPTOP-EVMCT3AM;Initial Catalog=dbESCOLA;Integrated Security=True";

// criar um método para que possa ser evocado sempre que necessário
private void CarregaCursos()
{
    string sql = "SELECT Id, NomeCurso FROM tbCURSO";

    using(SqlConnection conn = new SqlConnection(connString))
    {
        conn.Open();

        using(SqlCommand cmd = new SqlCommand(sql, conn))
        {
            SqlDataReader dr = cmd.ExecuteReader();
            DataTable dt = new DataTable();

            dt.Load(dr);

            cmbCurso.DataSource = null;
            cmbCurso.DataSource = dt;
            cmbCurso.DisplayMember = "NomeCurso"
            cmbCurso.ValueMember = "Id";
        }
    }
}

private void ConfigCursoUC_Load(object sender, EventArgs e)
{
    // evocar o método no Load do Form
    CarregaCursos();
}

private void btnCadastrarCurso(object sender, EventArgs e)
{
    // código para cadastrar o curso
    // ...

    // evocar o método após cadastrar o curso
    CarregaCursos();
}

In this example the connection is open and closed whenever we do the query, but you can choose to open the connection when you open the Form and close only when you close it:

// colocar a ConnectionString como variável global ao Form
private string connString = "Data Source=LAPTOP-EVMCT3AM;Initial Catalog=dbESCOLA;Integrated Security=True";
// colocar a conexão como variável global ao Form
private SqlConnection conn = null;

// criar um método para que possa ser evocado sempre que necessário
private void CarregaCursos()
{
    string sql = "SELECT Id, NomeCurso FROM tbCURSO";

    using(SqlCommand cmd = new SqlCommand(sql, conn))
    {
        SqlDataReader dr = cmd.ExecuteReader();
        DataTable dt = new DataTable();

        dt.Load(dr);

        cmbCurso.DataSource = null;
        cmbCurso.DataSource = dt;
        cmbCurso.DisplayMember = "NomeCurso"
        cmbCurso.ValueMember = "Id";
    }
}

private void ConfigCursoUC_Load(object sender, EventArgs e)
{
    // abrir a conexão
    AbreConexao();
    // evocar o método no Load do Form
    CarregaCursos();
}

private void ConfigCursoUC_FormClosed(object sender, FormClosedEventArgs e)
{
    // fechar a conexão
    FechaConexao();
}

private void btnCadastrarCurso(object sender, EventArgs e)
{
    // código para cadastrar o curso
    // ...

    // evocar o método após cadastrar o curso
    CarregaCursos();
}

private void AbreConexao()
{
    try
    {
        conn = new SqlConnection(connString);
        conn.Open();
    }
    catch(Exception ex)
    {
        MessageBox.Show("Ocorreu um erro ao abrir a conexão: " + ex.Message);
    }
}

private void FechaConexao()
{
    try
    {
        if (conn.State != ConnectionState.Closed)
            conn.Close();
    }
    catch(Exception ex)
    {
        MessageBox.Show("Ocorreu um erro ao fechar a conexão: " + ex.Message);
    }
}
  • 1

    If the answer was useful to you, do not forget to give a UP! :)

Browser other questions tagged

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