Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must declare the scalar variable error when inserting a foreign key

I am having this problem when I'm trying to insert data into a database with a button and textboxes. Everything works fine except a foreign key that is inside the table throws this error:

Must declare the scalar variable "@IDprodajalne"

I am getting kind of desperate so I really need your help now.

if (textBoxImeProdajalca.Text != "" && textBoxPriimekProdajalca.Text != "")
{
    try
    {
        string query = "insert into Prodajalec values (@IDProadajalne, @ImeProdajalca, @PriimekProdajalca)";

        using (connection = new SqlConnection(connectionString)
        using (SqlCommand command = new SqlCommand(query, connection))
        {
            connection.Open();
            command.Parameters.AddWithValue("@IDProdajalne", ComboBoxIDprodajalne.SelectedItem.ToString());
            command.Parameters.AddWithValue("@ImeProdajalca", textBoxImeProdajalca.Text);
            command.Parameters.AddWithValue("@PriimekProdajalca", textBoxPriimekProdajalca.Text);

            command.ExecuteNonQuery();
        }

        MessageBox.Show("Uspešno dodano");
    }
    catch(Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
else
{
    MessageBox.Show("Vnesite vse podatke");
}

And the string declarations

SqlConnection connection;
string connectionString;

public Form1()
{
        InitializeComponent();
        connectionString = ConfigurationManager.ConnectionStrings["Naloga.Properties.Settings.ProdajaConnectionString"].ConnectionString;
}
like image 712
David Borštner Avatar asked Feb 10 '26 15:02

David Borštner


1 Answers

Copy "IDprodajalne" from the error. Press Ctrl+F to search your question for it. It appears twice, both in this line:

command.Parameters.AddWithValue("@IDProdajalne", ComboBoxIDprodajalne.SelectedItem.ToString());

It does not appear in this line:

string query = "insert into Prodajalec values (@IDProadajalne,@ImeProdajalca,@PriimekProdajalca)";

"IDProadajalne" is a different string from "IDProdajalne". It has another "a" in it.

Fix the spelling of the one in query:

string query = "insert into Prodajalec values (@IDProdajalne,@ImeProdajalca,@PriimekProdajalca)";
like image 189
15ee8f99-57ff-4f92-890c-b56153 Avatar answered Feb 12 '26 15:02

15ee8f99-57ff-4f92-890c-b56153



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!