Fill a Combox with the current value of my Database

this is Guilherme here. I have a situation: Whenever I update a client on the application I’m trying to make, it simply captures the current value of the ComboBox to all the clients on my list. I’m working with a DataGridView, and the DataGrid prints the new value correct; however, the combobox doesn’t.

Like said above, if I update a client, that ComboBox will keep the same value to all clients; it won’t get the current value to each client in my Database. And if I restart the application or simply if I don’t update a client, it will get the SelectedIndex set for default, instead of the one related to the client. Here’s how my current code works… Please help!!

//UPDATING METHOD, INSIDE CRUD CLASS//

public void UpdateClient(int id_cliente, string[] rowsDB, string[] rowsForms)

        {
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                try
                {
                    connection.Open();


                    string updateQuery = "UPDATE cliente SET ";
                    for (int i = 0; i < rowsDB.Length; i++)
                    {
                        updateQuery += $"{rowsBD[i]} = @{rowsBD[i]}";
                        if (i < rowsDB.Length - 1)
                            updateQuery += ", ";
                    }
                    updateQuery += " WHERE id_cliente = @id_cliente";

                    using (MySqlCommand command = new MySqlCommand(updateQuery, connection))
                    {

                        for (int i = 0; i < rowsDB.Length; i++)
                        {
                            command.Parameters.AddWithValue($"@{rowsDB[i]}", rowsForms[i]);
                        }
                        command.Parameters.AddWithValue("@id_cliente", id_cliente);

                        int rowsAffected = command.ExecuteNonQuery();

                        if (rowsAffected > 0)
                        {
                            MessageBox.Show("Cliente atualizado com sucesso!");
                        }
                        else
                        {
                            MessageBox.Show("Cliente não encontrado ou nenhum campo foi alterado.");
                        }
                    }
                }

                catch (Exception ex)

                {
                    MessageBox.Show("Ocorreu um erro ao atualizar o cliente: " + ex.Message);
                }
            }
        }
//ABOVE, UPDATING METHOD, inside CRUD class.


//FUNCTIONAL BUTTON BELOW

private void Estados()
        {
            cb_Estado.Items.Add("AC Acre");
            cb_Estado.Items.Add("AL Alagoas");
            cb_Estado.Items.Add("AP Amapá");
            cb_Estado.Items.Add("AM Amazonas");
            cb_Estado.Items.Add("BA Bahia");
            cb_Estado.Items.Add("CE Ceará");
            cb_Estado.Items.Add("DF Distrito Federal");
            cb_Estado.Items.Add("ES Espírito Santo");
            cb_Estado.Items.Add("GO Goiás");
            cb_Estado.Items.Add("MA Maranhão");
            cb_Estado.Items.Add("MT Mato Grosso");
            cb_Estado.Items.Add("MS Mato Grosso do Sul");
            cb_Estado.Items.Add("MG Minas Gerais");
            cb_Estado.Items.Add("PA Pará");
            cb_Estado.Items.Add("PB Paraíba");
            cb_Estado.Items.Add("PR Paraná");
            cb_Estado.Items.Add("PE Pernambuco");
            cb_Estado.Items.Add("PI Piauí");
            cb_Estado.Items.Add("RJ Rio de Janeiro");
            cb_Estado.Items.Add("RN Rio Grande do Norte");
            cb_Estado.Items.Add("RS Rio Grande do Sul");
            cb_Estado.Items.Add("RO Rondônia");
            cb_Estado.Items.Add("RR Roraima");
            cb_Estado.Items.Add("SC Santa Catarina");
            cb_Estado.Items.Add("SP São Paulo");
            cb_Estado.Items.Add("SE Sergipe");
            cb_Estado.Items.Add("TO Tocantins");

            cb_Estado.SelectedIndex = 24;

           
        }


private void SelectedClientAutoFill()
        {
            if (dataGridView_Clientes.SelectedRows.Count > 0)
            {
                DataGridViewRow selectedRow = dataGridView_Clientes.SelectedRows[0];

                // Preencha os campos do formulário com os dados do cliente selecionado
                tb_NomeCliente.Text = selectedRow.Cells["Nome"].Value.ToString();
                tb_EmailCliente.Text = selectedRow.Cells["Email"].Value.ToString();
                tb_TelefoneCliente.Text = selectedRow.Cells["Telefone"].Value.ToString();
                tb_EnderecoCliente.Text = selectedRow.Cells["Endereço"].Value.ToString();
                cb_TipoCliente.SelectedItem = selectedRow.Cells["Tipo de Cliente"].RowIndex.ToString();
                tb_CpfCliente.Text = selectedRow.Cells["CPF/CNPJ"].Value.ToString();
                tb_Numero.Text = selectedRow.Cells["Número"].Value.ToString();
                tb_BairroCliente.Text = selectedRow.Cells["Bairro"].Value.ToString();
                tb_CidadeCliente.Text = selectedRow.Cells["Cidade"].Value.ToString();
                cb_Estado.SelectedItem = selectedRow.Cells["Estado"].RowIndex.ToString();
                
            }

[...]

 private void UpdateDataGridView()
        {
            string connectionString = "datasource=localhost;username=root;password=;database=projeto_integrador";
            dataGridView_Clientes.Rows.Clear();

            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                string query = "SELECT * FROM cliente";
                MySqlCommand command = new MySqlCommand(query, connection);

                connection.Open();
                MySqlDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {
                    int idCliente = Convert.ToInt32(reader["id_cliente"]);
                    string nome = reader["nome"].ToString();
                    string email = reader["email"].ToString();
                    string telefone = reader["telefone"].ToString();
                    string endereco = reader["endereco"].ToString();
                    string tipo_cliente = reader["tipo_cliente"].ToString();
                    string cpf_cnpj = reader["cpf_cnpj"].ToString();
                    int numero = Convert.ToInt32(reader["numero"]);
                    string bairro = reader["bairro"].ToString();
                    string cidade = reader["cidade"].ToString();
                    string estado = reader["estado"].ToString();

                    dataGridView_Clientes.Rows.Add(idCliente, nome, email, telefone, endereco, tipo_cliente, cpf_cnpj, numero, bairro, cidade, estado);
                }

                reader.Close();

                SelectedClientAutoFill();
            }
        }

 private void ib_Update_Client_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridView_Clientes.SelectedRows.Count > 0)
                {
                    // Obtém o ID do cliente selecionado
                    int id_cliente =   Convert.ToInt32(dataGridView_Clientes.SelectedRows[0].Cells["ID"].Value);

                    // Verifica se algum campo foi alterado no formulário
                    if (AlteredRows())
                    {
                        // Defina os campos do banco de dados e do formulário que devem ser atualizados
                        string[] camposBD = { "nome", "email", "telefone", "endereco", "tipo_cliente", "cpf_cnpj", "numero", "bairro", "cidade", "estado" };
                        string[] camposForms = { tb_NomeCliente.Text, tb_EmailCliente.Text,   tb_TelefoneCliente.Text, tb_EnderecoCliente.Text, cb_TipoCliente.SelectedItem.ToString(),    tb_CpfCliente.Text, tb_Numero.Text, tb_BairroCliente.Text, tb_CidadeCliente.Text, cb_Estado.SelectedItem.ToString() };

                        // Chama o método AlteraCliente com os dados do cliente
                        consulta.AlteraCliente(id_cliente, camposBD, camposForms);

                        // Atualiza o DataGridView após a alteração
                        
                        //Already tried bringing AlteredRows() here, but to no avail. (This function verifies if there's any altered info on my App's Forms, and seemingly works fine)
                        UpdateDataGridView();
                    }
                    else
                    {
                        MessageBox.Show("Nenhum campo foi alterado.");
                    }

First time using this, so again, I just want a solution to this issue. Not sure if it’s the proper way to write the question… xD

New contributor

lGuilherme is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật