Question

I have "Must declare scalar variable @BillNo" problem in this code don't know how to fix it. i'm very new to C# and programming. I've commented other scalar variables to understand but still have the problem. Data inserts when i don't use scalar variable but i need to use them.

private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                db = new DBConnection();

                String Sqlstr1 = "select UnitPrice from AItem where ItemID = '" + tbItemID.Text + "'";
                db.DataRead(Sqlstr1);
                int UnitPrice = Convert.ToInt32(db.dr["UnitPrice"]);
                int qty = Convert.ToInt32(tbQuantity.Text);          
                int sum = (UnitPrice * qty);

                String fday = Convert.ToString(db.now.AddDays(7));

                int billno = DateTime.Now.DayOfYear;



                String Sqlstr3 = "insert into Sales (ItemID ,BillNo ,Qty ,Sum, FinalDay) values ('" + tbItemID.Text + "' ,@BillNo,'" + qty + "' ,'" + sum + "' ,'" + fday + "' )";


                //db.cmd.Parameters.AddWithValue("@ItemID", tbItemID.Text);
                db.cmd.Parameters.AddWithValue("@BillNo" , billno);
                //db.cmd.Parameters.AddWithValue("@Qty", tbQuantity.Text);
                //db.cmd.Parameters.AddWithValue("@Sum", (UnitPrice * qty));   
                //db.cmd.Parameters.AddWithValue("@FinalDay", db.now.AddDays(7)); 

                if (db.Execute(Sqlstr3) == 1)
                {
                    MessageBox.Show("added");
                }
                else
                {
                    MessageBox.Show("something went wrong");
                }    


            }
            catch (SqlException m)
            {
                MessageBox.Show(m.Message);

            }
            catch (NullReferenceException m)
            {
                MessageBox.Show(m.Message);

            }
            catch (InvalidOperationException m)
            {
                MessageBox.Show(m.Message);

            }
    }
}
Was it helpful?

Solution

You shoud not execute a string but execute a DbCommand. So first create a DbCommand using your open DbConnection, set the Commandtext to your string, add all the parameters (e.g. @BillNo) and then execute the command.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top