I'm trying to use a function via a SQL connection I've done everywhere else in my application (only here it give the error, not the rest of the application). When i searched for what that error code meant the responses i found say it's an error when one can't connect to SQL server? but it doesn't give a solution.
here is my c# code
 SqlConnection connection = Database.GetConnection();
                DataTable dt = new DataTable("CRC");
                SqlCommand cmd = new SqlCommand("SELECT dbo.CalcRentalCharge(@RentalStartDateTime,@RentalEndDateTime,@CarTypeID)", connection);
            try
        {
            connection.Open();
            using (SqlDataReader dr = cmd.ExecuteReader())
            {
                cmd.CommandType = CommandType.Text;
                cmd.Parameters.Add("@RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
                cmd.Parameters.Add("@RentalEndDateTimetext", SqlDbType.DateTime).Value = RentalEndDateTimeBox.Text;
                cmd.Parameters.Add("@CarTypeIDtext", SqlDbType.Int).Value = CarTypeID.Text;
                connection.Open();
                Decimal rentalChange = (Decimal)cmd.ExecuteScalar();
                connection.Close();
                MessageBox.Show("The rental change is: " + rentalChange.ToString());
                if (dr.HasRows)
                {
                    dt.Load(dr);
                    dataGridView1.DataSource = dt;
                }
            }
            connection.Close();
Can you help me get this FUNCTION to work?
Don't use cmd.ExecuteReader() before adding parameter to command object.
It gives error,
add parameter to command and then cmd.execureReader()
You have a copy/paste error in your variable name:
In the line
cmd.Parameters.Add("@RentalStartDateTimetext", SqlDbType.DateTime).Value = RentalStartDateTimeBox.Text;
the string
RentalStartDateTimetext
needs to be
RentalStartDateTime
In addition to that, because it will pop up as your next error: Your opening and closing of the connection is wrong. Use a using block for the connection as well and open it directly after the start of the block. You don't need to close it manually, the using-block will do that for you.
 nvoigt
 nvoigtUser contributions licensed under CC BY-SA 3.0