Search code examples
c#visual-studiovisual-studio-2013sql-server-2014-express

Convert text into date format in Visual Studio 2013 using C# and save it in SQL Server 2014


I want to convert text into date format in Visual Studio 2013 by using C#. Alas! I am getting difficulties in it. I also want to save this data in SQL Server 2014.

My code is

protected void Button1_Click(object sender, EventArgs e)
        {
            con.Open();
            SqlCommand cmd = con.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText= "insert into Optical values('"+date.Text+"','"+name.Text+"','"+guardian.Text+"','"+gender.Text+"','"+age.Text+"','"+address.Text+"','"+occupation.Text+"','"+telephone.Text
                +"','"+sph.Text+"','"+cyl.Text+"','"+axis.Text+"','"+prism.Text+"','"+lsph.Text+"','"+lcyl.Text+"','"+laxis.Text+"','"+lprism.Text+"','"+note.Text+"')";
            cmd.ExecuteNonQuery();

            con.Close();
        }

I want to change just date's text into date format. Please anybody guide me, how can I do it?


Solution

  • DateTime.TryParseExact() is probably a better option but you could use regular expressions to ensure that the text entered is in the correct format to begin with. You can display the format that you desire in a placeholder ("Format must be yyyy-MM-dd") on your form. To be saved in SQL Server the string could look like this "yyyy-MM-dd HH:mm:ss"