This Way:
<form id="form1" runat="server">
<div>
Enter Date
<br />
<asp:TextBox ID="txtDOB" runat="server" />
<asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar_OnSelectionChanged">
</asp:Calendar>
<asp:Button ID="btn" runat="server" Text="Save" OnClick="Save" />
</div>
</form>
C#:
protected void Calendar_OnSelectionChanged(object sender, EventArgs e)
{
this.txtDOB.Text = this.Calendar1.SelectedDate.ToString();
}
protected void Save(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
string sqlStatment = "INSERT INTO DateOfBirth VALUES(@DOB)";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand(sqlStatment, con))
{
con.Open();
cmd.Parameters.AddWithValue("@DOB", Convert.ToDateTime(this.txtDOB.Text));
cmd.ExecuteNonQuery();
con.Close();
}
}
}
SQL Table:
CREATE TABLE [dbo].[DateOfBirth](
[Id] [int] IDENTITY(1,1) NOT NULL,
[DoB] [datetime] NOT NULL,
CONSTRAINT [PK_DateOfBirth] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
I have added asp Calendar control also. If you type Date as dd/MM/yyyy then it will give your error like String was not recognized as a valid DateTime. but it will allow you for these date format MM/dd/yyyy and yyyy/MM/dd.
Thank You.