There is a property named
Value
in the
DateTimePicker
. Use that instead of converting the text to
DateTime
. The value directly returns a DateTime object containing the value of the
DateTimePicker
. Also, use
SqlParameter
to send the data with the SQL.
using (SqlConnection connection = new SqlConnection())
{
try
{
connection.ConnectionString = "Data Source=SW-PC-20;Integrated security =SSPI;Initial catalog=PSM";
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Campaign(Campaign_id,List_of_thresholds,Duration,Starting_Date,Ending_Date,Total_Budget_of_all_thresholds) VALUES(@Campaign_id,@List_of_thresholds,@Duration,@Starting_Date,@Ending_Date,@Total_Budget_of_all_thresholds)";
command.CommandType = CommandType.Text;
SqlParameter campainIdParameter = command.CreateParameter();
campainIdParameter.ParameterName = "@Campaign_id";
campainIdParameter.Value = this.cbocampaign.Text;
command.Parameters.Add(campainIdParameter);
SqlParameter listOfThresholdsParameter = command.CreateParameter();
listOfThresholdsParameter.ParameterName = "@List_of_thresholds";
listOfThresholdsParameter.Value = this.cbolist_threshold.Text;
command.Parameters.Add(listOfThresholdsParameter);
SqlParameter durationParameter = command.CreateParameter();
durationParameter.ParameterName = "@Duration";
durationParameter.Value = this.txtduration.Text;
command.Parameters.Add(durationParameter);
SqlParameter startingDateParameter = command.CreateParameter();
startingDateParameter.ParameterName = "@Starting_Date";
startingDateParameter.Value = this.DateTimePicker1.Value;
command.Parameters.Add(startingDateParameter);
SqlParameter endingDateParameter = command.CreateParameter();
endingDateParameter.ParameterName = "@Ending_Date";
endingDateParameter.Value = this.DateTimePicker2.Value;
command.Parameters.Add(endingDateParameter);
SqlParameter totalBudgetParameter = command.CreateParameter();
totalBudgetParameter.ParameterName = "@Total_Budget_of_all_thresholds";
totalBudgetParameter.Value = this.txtbudget.Text;
command.Parameters.Add(totalBudgetParameter);
connection.Open();
int affectedRows = command.ExecuteNonQuery();
}
}
finally
{
if ((connection != null) && (connection.State == ConnectionState.Open))
try { connection.Close(); }
catch { }
}
}
If a sql exception occurs saying some parameter is not in correct format, just cast it to the respective data type like
(int)cbocampaign.Text;
NOTE: This is how you really use these
SqlConnection
and
SqlCommand
objects. Hope you would learn something out of this. Also, you should really start naming your controls in a readable manner :)
Hope this helps :) Regards