decimals from c # to sql server

1

rephrase my question that is more accurate, I try to insert a decimal from c # to sql server.

This is the click event of the button save the connection but does not do it

private void btnBunifuGuardarCargoDirecto_Click(object sender, EventArgs e)

 {

try



 {




SqlConnection Conn = BDComun.ObtenerConexion();

     SqlCommand consulta = new SqlCommand("insert into cargoDirecto(costoUnitario) values(@costoUnitario)", Conn);

                consulta.Parameters.AddWithValue(",@costoUnitario", Convert.ToDecimal(txtCostoUnitarioCargoDirecto.Text.Replace(",",".")));
                consulta.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex);
            }
        }

It does not connect me to the bd and it does not insert, I do not know what it can be, Thanks for your time and help friends!

    
asked by Patricio Riquelme 13.11.2018 в 20:55
source

2 answers

1

Remember that you have to respect the data type of each parameter, then you should use

cmd.Parameters.AddWithValue("@fecha", dateTimePickerFechaCargoDirecto.Value);

if you use a DateTimePicker this returns a DateTime with property Value

If you are going to define a numerical value you should also respect it

cmd.Parameters.AddWithValue("@costoUnitario", Convert.ToDecimal(txtCostoUnitarioCargoDirecto.Text));

cmd.Parameters.AddWithValue("@cantidad", Convert.ToInt32(txtCantidadCargoDirecto.Text));

either decimal or int you must convert the string to these data types

    
answered by 13.11.2018 в 21:17
0

First I see that you have 2 parameters with the name wrongly written since you include ","

cmd.Parameters.AddWithValue(",@costoUnitario", txtCostoUnitarioCargoDirecto.Text);
cmd.Parameters.AddWithValue(",@@costoTotalCargoDirecto", txtCostoTotalCargoDirecto.Text);

In addition to this if you want to save decimals in the database you must validate the COLLATION of it, for example if Modern_Spanish_CI_AI you will use " , " to separate decimals (even though when opening the SSMS it will be see as points) so the value you retrieve from TextBox should use a mask to only receive " , " or you can before saving the value in the database use a REPLACE in the textbox ( REPLACE(txtCostoTotalCargoDirecto.Text,".","," ).

I hope it helps you.

    
answered by 14.11.2018 в 10:19