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
lGuilherme is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.