0

I want to save date through textbox to a SQL Server database using parameters as below:

SqlParameter p15 = new SqlParameter
{   
    SqlDbType = SqlDbType.Date,
    ParameterName = "prj_start_date",
    SqlValue = txtStartDate.Text
};

and the following error appear:

Conversion failed when converting the nvarchar value '12-12-2015' to data type int.

I have try use casting using convert but this was not worked

In addition textmode= date doesn't work in IE

Thanks in advance

3
  • 2
    Use debug, search in google how to use debug in C#! You are trying to convert 12-12-2015 to int somewhere, because of that you have this problem. Commented Jan 9, 2016 at 14:32
  • May be try 2015-12-12 once. Commented Jan 9, 2016 at 14:43
  • Thank u Appreciate you efforts. Commented Jan 9, 2016 at 15:25

2 Answers 2

1

It would be better if you use a jQuery DatePicker rather than using a user input which would save you from invalid inputs from end users.

You are getting this error because you are passing a String type to a Date Type.

Try this:

string enteredDate = txtStartDate.Text.Trim();
DateTime date = DateTime.Parse(enteredDate, InvariantCulture);

SqlParameter p15 = new SqlParameter
{
    SqlDbType = SqlDbType.Date,
    ParameterName = "prj_start_date",
    SqlValue = date;
};
Sign up to request clarification or add additional context in comments.

2 Comments

But how if i want to leave the textbox of date is null ??
You can check while passing SqlParameter if textbox value is empty. if(String.IsNullorEmpty(txtStartDate.Text.Trim())) { SqlDateTime s = SqlDateTime.Null; } And pass s as value to your Sqlparameter
0

Have you considered parsing the text into a DateTime object in C# - ParseExact allows you to give a specific format string. Then you do not have to deal with Text on the SQL level, particularly given that your date form is non-ISO-standard and open to cultural interpretation.

1 Comment

Thank U :) Appreciate you efforts.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.