Search code examples
c#asp.netsql-servernvarchar

Cannot convert data type nvarchar to numeric


get this error to the txtNum.Text i dont know what to do i already tried the

Convert.ToInt32 and SqlDbType.Int but it doesnt work please help me

the total has a $ sign in it maybe that's the problem. the Total's DataType is Decimal

com = new SqlCommand(@"INSERT INTO Orders(
                        OrderDate, 
                        Username, 
                        FirstName, 
                        LastName, 
                        Address, 
                        Phone, 
                        Total, 
                        HasBeenShipped
                    ) 
                    VALUES(
                        GetDate(),
                        @p5, 
                        @p1, 
                        @p2, 
                        @p3, 
                        @p4, 
                        @p6,
                        'false'
                    )", con2);
com.Parameters.AddWithValue("@p5", Label2.Text);
com.Parameters.AddWithValue("@p1", txtFname.Text);
com.Parameters.AddWithValue("@p2", TxtLname.Text);
com.Parameters.AddWithValue("@p3", TxtAdd.Text);
com.Parameters.AddWithValue("@p4", Convert.ToInt32(TxtNum.Text));
com.Parameters.AddWithValue("@p6", lblTotal.Text);
com.ExecuteNonQuery();

Solution

  • If lblTotal is formatted as a currency then you can use:

    com.Parameters.AddWithValue("@p6", Decimal.Parse(lblTotal.Text,NumberStyles.Currency));
    

    Obviously it will throw an exception if it's not a valid currency value - you'd need to decide what to do in that case.