We have a form on our aspx page with a number of textboxes. We would like to UPDATE several tables in our sql server database with the values inputted into these text boxes however if any of the text boxes are left blank we would like to leave the data for that column as it is, currently it won't accept empty values.
If all textboxes are filled, it functions correctly, if not, we get the error: Input string was not in a correct format.
Code fired when submit button is clicked:
protected void buttonClicked(object sender, EventArgs e)
{
string CS = ConfigurationManager.ConnectionStrings["G4StowawaysConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(CS);
conn.Open();
String sql5 = "" ;
if ([email protected](null) | [email protected](null))
{
sql5 += "UPDATE BookingView SET ";
if ([email protected](null))
{
sql5 += " [Balance_Outstanding]=@BalanceOutstanding,";
}
if ([email protected](null))
{
sql5 += " [Comments]=@Comments ";
}
sql5 += "WHERE [Booking_Ref] = @BookingRef;";
}
if ([email protected](null) | [email protected](null) | [email protected](null) | [email protected](null) | [email protected](null) | [email protected](null) | [email protected](null))
{
sql5 += "UPDATE vBoat_Booking SET";
if ([email protected](null))
{
sql5 += " [BoatID]=@BoatID,";
}
if ([email protected](null))
{
sql5 += " [Special_Request]=@SpecialRequests,";
}
if ([email protected](null))
{
sql5 += " [Lead_PassengerID]=@LeadPassenger,";
}
if ([email protected](null))
{
sql5 += " [Duration_In_Hours]=@Duration,";
}
if ([email protected](null))
{
sql5 += " [Number_of_pets]=@Pets,";
}
if ([email protected](null))
{
sql5 += " [Number_of_children]=@Children,";
}
if ([email protected](null))
{
sql5 += " [Number_of_passengers]=@Passengers ";
}
sql5 += "WHERE [Booking_Ref] = @BookingRef;";
}
SqlCommand cmd2 = new SqlCommand(sql5, conn);
//add our parameters to our command object
cmd2.Parameters.AddWithValue("@BookingRef", Convert.ToInt32(BookingRef.Text));
cmd2.Parameters.AddWithValue("@BoatID", Convert.ToInt32(BoatID.Text));
cmd2.Parameters.AddWithValue("@LeadPassenger", Convert.ToInt32(LeadPassenger.Text));
cmd2.Parameters.AddWithValue("@Duration", Convert.ToInt32(Duration.Text));
cmd2.Parameters.AddWithValue("@Pets", Convert.ToInt32(Pets.Text));
cmd2.Parameters.AddWithValue("@Children", Convert.ToInt32(Children.Text));
cmd2.Parameters.AddWithValue("@Passengers", Convert.ToInt32(Passengers.Text));
cmd2.Parameters.AddWithValue("@SpecialRequests", SpecialRequests.Text);
cmd2.Parameters.AddWithValue("@BalanceOutstanding", Convert.ToInt32(BalanceOutstanding.Text));
cmd2.Parameters.AddWithValue("@Comments", Comments.Text);
cmd2.ExecuteNonQuery();
conn.Close();
}
sql5 += " [Balance_Outstanding]=@BalanceOutstanding,";leaves the SQL ending with a comma (if that's the only field being updated). A better approach may be to use stored procedures to hold the logic as follows: stackoverflow.com/questions/15569860/…