Domanda

I'm completely new to the SQL command parameters (I have been briefly explained this concept yesterday, and might not get it) and generally to the OOP but I enjoy it :D

Here is the link to my question from yesterday ;) Guys have really helped, but I now struggle to implement this in my app

I have actually built as an example:

  • Form "formConnection.cs" containing 2 user inputs "comboBoxEmployeeId" (selectedvalue is a int) + "txtDuration" (value is a decimal), on a click on "btnInsert" I process this: `

    sqlDbOperations sqlDbOp = new sqlDbOperations();`
    
    public void btnInsert_Click(object sender, EventArgs e)
    {
        //Create new contract
        var contract = new contract{
            employeeId = Convert.ToInt32(this.comboBoxEmployeeName.SelectedValue),
            duration = Convert.ToDecimal(this.txtDuration.Text)
        };
    
        //Insert command to Db
        sqlDbOp.insertContract();
    
        MessageBox.Show("Done");
    }
    
  • Class "contract.cs"

    class contract { public int employeeId { get; set; } public decimal duration { get; set; } }

  • Class "sqlDbOperations.cs"

    public class sqlDbOperations { //Connection string //SqlConnection myConnection = new SqlConnection("ATLELAG786576\SQLEXPRESS;Initial Catalog=TEST;Integrated Security=False;Connect Timeout=30;User Instance=False;User ID=basicuser;Password=basicpw"); SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["EngAdminSqlDbConnectionString"].ConnectionString);

        //Connection open
        //SqlConnection.Open() is a void function and does not return an error but throws an exception so remember to put it in a try/catch brace
        //Rather than having the program explode in front of the user
        public void openConnection()
        {
            //Connection open
            try
            {
                myConnection.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                MessageBox.Show(e.ToString());
            }
        }
    
        //Connection close
        //Try/catch because like SqlConnection.Open() it does not return errors but throws an exception instead
        public void closeConnection()
        {
            try
            {
                myConnection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    
        contract contract = new contract();
    
        public void insertContract()
        {
            //Open
            openConnection();
    
            //Command
            SqlCommand myCommand = new SqlCommand("INSERT INTO tblContracts (EmployeeId, Duration) VALUES (@employeeId, @contractDuration)", myConnection);
    
            //Get values from form
            formConnection formInput = new formConnection();
    
            //Add parameters
            myCommand.Parameters.AddWithValue("@employeeId", contract.employeeId);
            myCommand.Parameters.AddWithValue("@contractDuration", contract.duration);
    
    
            //Execute
            myCommand.ExecuteNonQuery();
    
            //Close
            closeConnection();
    
    
    
    
        }
    }
    

This works without working - When I put a "decimal" value like 2.7 in my txtDuration textbox I still got a message:

System.FormatException: Le format de la chaîne d'entrée est incorrect. = "The input string format is not correct" à System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) à System.Number.ParseDecimal(String value, NumberStyles options, NumberFormatInfo numfmt) à System.Convert.ToDecimal(String value) à SQLStatementParameters.formConnection.btnInsert_Click(Object sender, EventArgs e) dans D:\C#\Projects\SQLStatementParameters\SQLStatementParameters\formConnection.cs:ligne 26 à System.Windows.Forms.Control.OnClick(EventArgs e)".....

  • Nothing is stored in the DB (as if the values are not transported from the form to the object 'contract' then to the method that does the INSERT), I have a new record but it's all empty

What am I doing wrong? Thank you for your help!

Brice

È stato utile?

Soluzione

The values are not transported into your sql command actually. The instance of class contract which you create in the class 'sqlDbOperations' is different from the one you create in btnInsert_Click. And you need to transport the one created in btnInsert_Click to sqlDbOp.insertContract(); to insert into DB.

So you can do something like this:

public void insertContract(contract con)
{
    //Open
    openConnection();

    //Command
    SqlCommand myCommand = new SqlCommand("INSERT INTO tblContracts (EmployeeId,   Duration) VALUES (@employeeId, @contractDuration)", myConnection);

    //Get values from form
    formConnection formInput = new formConnection();

    //Add parameters
    myCommand.Parameters.AddWithValue("@employeeId", con.employeeId);
    myCommand.Parameters.AddWithValue("@contractDuration", con.duration);


    //Execute
    myCommand.ExecuteNonQuery();

    //Close
    closeConnection();
}

And for the exception 'The input string format is not correct'. Maybe you can refer to this link

Altri suggerimenti

What is the dataType of Duration in your database, make sure that it should be numeric(19,6) or data type should be which accept the decimal values

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top