Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store date from text box in SQL Server through C# ASP.net

I am having trouble while storing date in sql server DB through C# asp.net, online

I have used asp Text box and asp calender extender in ASP file to get date from user,

 <asp:TextBox runat="server" ID="txt_date"></asp:TextBox>
<asp:CalendarExtender runat="server" ID="cal_date" TargetControlID="txt_date"></asp:CalendarExtender>

code behind file is, assume connection and command are declared and initialized ,

mycom = new SqlCommand("insert into mytable(dtCol1) values('"+Convert.ToDateTime(txt_dob.Text).ToString("dd-MMM-yyyy") + "')", mycon);mycom.ExecuteNonQuery();

Problem is, when I select date less than 12 of any month it works perfect, but when date/day is greater than 12 of any month it gives error,

Exception Details: System.FormatException: String was not recognized as a valid DateTime.

I have tried all combinations of .ToString("dd-MMM-yyyy")

Please Help thanks in advance

like image 960
Nils Avatar asked Feb 17 '23 13:02

Nils


2 Answers

try this

mycom = new SqlCommand("insert into mytable(dtCol1) values(@value1)");
mycom.Parameters.AddWithValue("@value1",Convert.ToDateTime(txt_dob.Text));
mycom.ExecuteNonQuery();
like image 168
Feras Salim Avatar answered May 03 '23 08:05

Feras Salim


Try this

CultureInfo provider = CultureInfo.InvariantCulture;
System.Globalization.DateTimeStyles style = DateTimeStyles.None;
DateTime dt;
DateTime.TryParseExact(txt_dob.Text, "m-d-yyyy", provider, style, out dt);
mycom = new SqlCommand("insert into mytable(dtCol1) values(@datevalue)", mycon);
cmd.Parameters.Add("@datevalue",SqlDbType.DateTime).Value =dt;
mycom.ExecuteNonQuery();
like image 34
Rajeev Kumar Avatar answered May 03 '23 07:05

Rajeev Kumar