Update inventory

0

I have a stored procedure to update the existence of my inventory. This is the code in SQL :

 ALTER PROCEDURE [dbo].[SP_ActualizaInventario]
 @cantidad INT
,@Producto INT
,@Tipo INT
AS
BEGIN
DECLARE @Existencia INT 
SET @Existencia = (SELECT Existencia FROM maestraproductoinventario WHERE [Codigo De Articulo] = @Producto)
if(@Tipo = 1)
begin
UPDATE
 maestraproductoinventario 
 SET
    Existencia = @Existencia - @cantidad 
    WHERE [Codigo De Articulo] = @Producto
end
else
begin
UPDATE
 maestraproductoinventario 
 SET
    Existencia = @Existencia + @cantidad 
    WHERE [Codigo De Articulo] = @Producto
end
END

I use it like this in c #:

SqlConnection conec = new SqlConnection();
SqlCommand cm = new SqlCommand();
cm.Connection = con;
cm.CommandText = "SP_ActualizaInventario";
cm.CommandType = CommandType.StoredProcedure;

cm.Parameters.Add(new SqlParameter("@cantidad", SqlDbType.Int));
cm.Parameters["@cantidad"].Value = txtcantidad.Text.Trim();

cm.Parameters.Add(new SqlParameter("@Producto", SqlDbType.Int));
cm.Parameters["@Producto"].Value = txtcodigo.Text.Trim();

cm.Parameters.Add(new SqlParameter("@Tipo", SqlDbType.Int));
cm.Parameters["@Tipo"].Value = 2;

con.Open();
cm.ExecuteNonQuery();

and when I use it in the purchase it gives me an error of type of data, it tells me this:

  

An unhandled exception of type 'System.FormatException' occurred in System.Data.dll   Additional information: Failed to convert parameter value from a String to a Int32.

I do not understand why, does anyone have an idea?

    
asked by Samuel Ignacio Susana Confesor 13.06.2017 в 01:30
source

1 answer

0

The problem I see in these two lines:

cm.Parameters.Add(new SqlParameter("@cantidad", SqlDbType.Int));
cm.Parameters["@cantidad"].Value = txtcantidad.Text.Trim();

Since in the first you are defining the type of column in Int , and in the second you are assigning a value string , what you should do is something like this in the second line:

cm.Parameters["@cantidad"].Value = Convert.ToInt32(txtcantidad.Text.Trim());

This is how you are converting the text that is in txtcantidad into a data of type whole number .

Better control over that might be doing it with int.TryParse :

int _dato = 0;
int.TryParse(txtcantidad.Text.Trim(), out _dato);
cm.Parameters["@cantidad"].Value = _dato;

to make sure you're always going to have a number. Finally, I'll leave this reference on text to number conversions so you can see what options there are.

    
answered by 13.06.2017 в 01:43