简体   繁体   中英

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?

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM