Insert numerical (decimal) data from textbox values

后端 未结 2 937
[愿得一人]
[愿得一人] 2021-01-26 12:01

I am confused by the following issue;

I have a C# (WindowsForms) application which I connect to a SQL Server DB and have no problem to INSERT, SELECT, UPDATE... until I

相关标签:
2条回答
  • 2021-01-26 12:20

    First of all, Always use using when dealing with SqlConnection and SqlCommand and all other classes that implements IDisposable just read more about it..

    Second thing, Always use parameters with SqlCommand and never pass the values as a string to the sql string. This is a serious security issue. In addition to that parameters makes your code human friendly!

    // Always use (using) when dealing with Sql Connections and Commands
    using (sqlConnection conn = new SqlConnection())
    {
        conn.Open();
    
        using (SqlCommand newCmd = new SqlCommand(conn))
        {
            newCmd.CommandType = CommandType.Text;
    
            newCmd.CommandText = 
                  @"INSERT INTO tblContracts (CreatedById, CreationDate, EmployeeId, Role, ContractType, StartDate, EndDate, Agency, LineManager, ReportTo, CostCenter, FunctionEng, AtrNo, AtrDate, PrNo, PrDate, PoNo, PoDate, Comments, Duration, WorkRatePercent, Currency, HourlyRate, Value) 
                  VALUES (@UserID, @CreationDate, @EmployeeID, @Role.....etc)";
    
            // for security reasons (Sql Injection attacks) always use parameters
            newCmd.Parameters.Add("@UserID", SqlDbType.NVarChar, 50)
                 .Value = connectedUser.getUserId();
    
            newCmd.Parameters.Add("@CreationDate", SqlDbType.DateTime)
                 .Value = DateTime.Now;
    
            // To add a decimal value from TextBox
            newCmd.Parameters.Add("@SomeValue", SqlDbType.Decimal)
                 .Value = System.Convert.ToDecimal(txtValueTextBox.Text);
    
            // complete the rest of the parameters
            // ........
    
            newCmd.ExecuteNonQuery();
    
            MessageBox.Show("Contract has been successfully created", "Completed", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
    }
    
    0 讨论(0)
  • 2021-01-26 12:33

    This is not a direct answer to your question, but please (!) replace this ugly method by this:

    Create a class for your contracts. This will make it much easier to handle contracts. If you have several methods handlings contracts in some way, you will not have to change the almost endless parameter lists of all of them, when properties are added to the contract.

    public class Contract
    {
        public int EmployeeID { get; set; }
        public string Agency { get; set; }
        public string Role { get; set; }
        ... and so on
    }
    

    and change the method signature to

    public void CreateNewContract(Contract contract)
    

    Headers of methods loading contracts form the database would look like this

    public List<Contract> LoadAllContracts()
    
    // Assuming contractID is the primary key
    public Contract LoadContractByID(int contractID)
    

    Much easier than returning 1000 variables!

    You can create a new contract with

    var contract = new Contract {
        EmployeeID = 22,
        Agency = "unknown",
        Role = "important", 
        ...
    };
    

    Also (as others have pointed out already) use command parameters.

    newCmd.Parameters.AddWithValue("@EmployeeID", contract.EmployeeID);
    newCmd.Parameters.AddWithValue("@Agency", contract.Agency);
    newCmd.Parameters.AddWithValue("@Role", contract.Role);
    

    (HaLaBi's post shows how to formulate your insert command string.)

    0 讨论(0)
提交回复
热议问题