Click here to Skip to main content
16,004,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm trying to use a combobox to set the ID of a company by using the name, which is like this

Caetano Coatings = 1
Dura = 2
And so on...

But atm i'm having issues with an error like this one on the title.

this is the code i have on my winform.
C#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace Portaria
{
    public partial class DarEntrada : Form
    {
        public DarEntrada()
        {
            InitializeComponent();
        }
        
        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void DarEntrada_Load(object sender, EventArgs e)
        {
            dateTimePicker1.Enabled = false;
            this.empresasTableAdapter.Fill(this.portariaDataSet.empresas);
            txtmatpers.Visible = false;
            txtsector.Enabled = false;
            FillDropDownList();
            SaveComboBoxContent();
        }

        public void FillDropDownList()
        {
            string SQL = "SELECT id_empresa, nome_empresa FROM empresas ORDER BY nome_empresa";

            DataTable dt = new DataTable();

           
            using (var cn = new MySqlConnection(@"server=localhost;user id=root;password=12345;persistsecurityinfo=True;database=portaria"))
            {
                using (var cmd = new MySqlCommand(SQL, cn))
                {
                    cn.Open();

                    try
                    {
                        dt.Load(cmd.ExecuteReader());
                    }
                    catch (MySqlException e)
                    {
                         
                        MessageBox.Show("Ocurreu um erro ao aceder á sua base de dados, contacte um administrador. Detalhe do erro: " + e.ToString());
                    }
                }
            }

            
            comboBox1.DataSource = dt;
            comboBox1.ValueMember = "id_empresa";
            comboBox1.DisplayMember = "nome_empresa";
        }


        public void SaveComboBoxContent()
        {
            string SQL = "INSERT INTO entradas (nome_empresa_id_empresa) VALUES (@nome_empresa_id_empresa)";

            using (var cn = new MySqlConnection("server = localhost; user id = root;password = 12345; persistsecurityinfo = True; database = portaria"))
            {
                using (var cmd = new MySqlCommand(SQL, cn))
                {
                    cmd.Parameters.AddWithValue("@name_id", comboBox1.SelectedValue);
                    cn.Open();

                    try
                    {
                        cmd.ExecuteNonQuery();
                    }
                    catch (MySqlException e)
                    {
                         
                        MessageBox.Show("There was an error accessing your data. DETAIL: " + e.ToString());
                    }
                }
            }
        }

        private void chkmatpers_CheckedChanged(object sender, EventArgs e)
        {
            
            
            try
            {
                if (chkmatpers.Checked == true)
                {
                    msktxtmat.Mask = null;   
                }else
                {
                    msktxtmat.Mask = "00-00-AA"; 
                }
            }catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkvariasemp_CheckedChanged(object sender, EventArgs e)
        {

            try
            {
                if (chkvariasemp.Checked == true)
                {
                    
                }
                else
                {
                    
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chksector_CheckedChanged(object sender, EventArgs e)
        {
            txtsector.Enabled = false;
            try
            {
                if(chksector.Checked == true)
                {
                    txtsector.Enabled = true;
                }
                else
                {
                    txtsector.Enabled = false;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void chkhoraentrada_CheckedChanged(object sender, EventArgs e)
        {
            dateTimePicker1.Enabled = false;
            try
            {
                if(chkhoraentrada.Checked == true)
                {
                    dateTimePicker1.Enabled = true;
                }
                else
                {
                    dateTimePicker1.Enabled = false;
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (chkmatpers.Checked)
            {

                DialogResult dr = MessageBox.Show("Deseja mesmo gravar estas alterações?", "Confirmação", MessageBoxButtons.YesNo,
                   MessageBoxIcon.Information);

                if (dr == DialogResult.Yes)
                {
                    string con = "server=localhost;userid=root;password=12345;persistsecurityinfo=True;database=portaria";
                    string query = "Insert into entradas(id_veiculo,empresa_visitante,empresa_visitar,nome_condutor,visitado,ncartao,data,hora,obs) values('"+ msktxtmat.Text +"','"+ txtempvis.Text +"','"+ comboBox1.SelectedValue +"', '"+ txtnomecondutor.Text +"','"+ txtpessoavisitar.Text +"', '"+ txtncartao.Text +"', '"+ DateTime.Now.ToString("yyyy-MM-dd") +"', '"+ DateTime.Now.ToShortTimeString() +"','"+ txtobs.Text +"');";
                    MySqlConnection Con = new MySqlConnection(con);
                    MySqlCommand Command = new MySqlCommand(query, Con);
                    MySqlDataAdapter sda = new MySqlDataAdapter();
                    DataTable dt = new DataTable();
                    sda.SelectCommand = Command;
                    sda.Fill(dt);
                }
            }else
            {
                DialogResult dr = MessageBox.Show("Deseja mesmo gravar estas alterações?", "Confirmação", MessageBoxButtons.YesNo,
                  MessageBoxIcon.Information);

                if (dr == DialogResult.Yes)
                {
                    string con = "server=localhost;userid=root;password=12345;persistsecurityinfo=True;database=portaria";
                    string query = "Insert into entradas(id_veiculo,empresa_visitante,empresa_visitar,nome_condutor,visitado,ncartao,data,hora,obs) values(@msktxtmat,@txtempvis,@comboBox1,@txtnomecondutor,@txtpessoavisitar,@txtncartao,@data,@horas,@txtobs);";
                    MySqlConnection Con = new MySqlConnection(con);
                    MySqlCommand Command = new MySqlCommand(query, Con);
                    Command.Parameters.AddWithValue("@msktxtmat", msktxtmat.Text);
                    Command.Parameters.AddWithValue("@txtempvis", txtempvis.Text);
                    Command.Parameters.AddWithValue("@comboBox1", comboBox1.SelectedValue);
                    Command.Parameters.AddWithValue("@txtnomecondutor", txtnomecondutor.Text);
                    Command.Parameters.AddWithValue("@txtpessoavisitar", txtpessoavisitar.Text);
                    Command.Parameters.AddWithValue("@txtncartao", txtncartao.Text);
                    Command.Parameters.AddWithValue("@data", DateTime.Now.ToString("yyyy-MM-dd"));
                    Command.Parameters.AddWithValue("@horas", DateTime.Now.ToString("hh:mm:ss"));
                    Command.Parameters.AddWithValue("@txtobs", txtobs.Text);
                    MySqlDataAdapter sda = new MySqlDataAdapter();
                    DataTable dt = new DataTable();
                    sda.SelectCommand = Command;
                    sda.Fill(dt);
                }
            }
            if(chkhoraentrada.Checked)
            {
                DialogResult dr = MessageBox.Show("Deseja mesmo gravar estas alterações?", "Confirmação", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Information);
                if (dr == DialogResult.Yes)
                {
                    string con = "server=localhost;userid=root;password=12345;persistsecurityinfo=True;database=portaria";
                    string query = "Insert into entradas(id_veiculo,empresa_visitante,empresa_visitar,nome_condutor,visitado,ncartao,data,hora,obs) values('" + msktxtmat.Text + "','" + txtempvis.Text + "','" + comboBox1.SelectedText + "', '" + txtnomecondutor.Text + "','" + txtpessoavisitar.Text + "', '" + txtncartao.Text + "', '" + DateTime.Now.ToString("yyyy-MM-dd") + "', '" + dateTimePicker1.Text + "','" + txtobs.Text + "');";
                    MySqlConnection Con = new MySqlConnection(con);
                    MySqlCommand Command = new MySqlCommand(query, Con);
                    MySqlDataAdapter sda = new MySqlDataAdapter();
                    DataTable dt = new DataTable();
                    sda.SelectCommand = Command;
                    sda.Fill(dt);

                }
            }
            else
            {
                DialogResult dr = MessageBox.Show("Deseja mesmo gravar estas alterações?", "Confirmação", MessageBoxButtons.YesNo,
                    MessageBoxIcon.Information);
                if (dr == DialogResult.Yes)
                {
                    string con = "server=localhost;userid=root;password=12345;persistsecurityinfo=True;database=portaria";
                    string query = "Insert into entradas(id_veiculo,empresa_visitante,empresa_visitar,nome_condutor,visitado,ncartao,data,hora,obs) values('" + msktxtmat.Text + "','" + txtempvis.Text + "','" + comboBox1.SelectedText + "', '" + txtnomecondutor.Text + "','" + txtpessoavisitar.Text + "', '" + txtncartao.Text + "', '" + DateTime.Now.ToString("yyyy-MM-dd") + "', '" + dateTimePicker1.Text + "','" + txtobs.Text + "');";
                    MySqlConnection Con = new MySqlConnection(con);
                    MySqlCommand Command = new MySqlCommand(query, Con);
                    MySqlDataAdapter sda = new MySqlDataAdapter();
                    DataTable dt = new DataTable();
                    sda.SelectCommand = Command;
                    sda.Fill(dt);

                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }
}


What I have tried:

Tried to use dataset on combobox to define the default value and the shown data.
Posted
Comments
phil.o 29-Feb-16 10:10am    
In your SaveComboBoxContent method, the name of the SQL parameter @name_id does not match the name of the parameter in the query (@nome_empresa_id_empresa); both parameter names should match.
Scribling Doodle 29-Feb-16 10:14am    
how it should be then? @nome_empresa_id_empresa? or keep the @name_id?

I'm really confused... I have a table which has a name and id for each company, but how can i tell my program that it should insert the id and not the name shown at the combobox? Could you help me out here please?
https://gyazo.com/ba5b1ce46780ae64c3e6a81da86f8b20
this is the default proprieties of combobox
phil.o 29-Feb-16 10:19am    
It's up to you; both names have to match, so both @name_id or both @nome_empresa_id_empresa, but not a mix of them.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900