Wednesday, 24 April 2013

How to store date and time separately using datetime picker in C#


Click Add New Item --> Select Windows Form --> Click Toolbox --> Select 2 datetime pickers as
dateTimePicker1 and dateTimePicker2.

Right Click on dateTimePicker1 --> Select properties --> Select Format --> Change it to Short .
Similarly Right Click on dateTimePicker2 --> Select properties --> Select Format --> Change it to Time .

Now Add an Button(button1) and name it as Insert.

Now Double click on the button, the coding .cs page will be opened. In that for the button click event write the following code.

private void button1_Click_1(object sender, EventArgs e)
{

datevalue = Convert.ToString(dateTimePicker1.Value);

DateTime tdate = DateTime.Now;

vdate = Convert.ToDateTime(datevalue);

datevalue= vdate.ToString("yyyy-MM-dd");

string timevalue = Convert.ToString(dateTimePicker2.Value);
DateTime vtime = DateTime.Now;

vtime= Convert.ToDateTime(timevalue);

timevalue = string.Format("{0}:{1} {2}", tt.Hour, tt.Minute, tt.Hour > 12 ? "PM" : "AM");

SqlConnection con = new SqlConnection ("Data Source=.\\SQLEXPRESS; Initial Catalog=sampledb;Integrated Security=True");

con.Open();

SqlCommand cmd = new SqlCommand("INSERT INTO TABLENAME (datefield,timefield)
VALUE ('" +datevalue+"','" +timevalue+"')", con); //Create database with fields datefield,timefield

cmd.ExecuteNonQuery();

con.Close();
}

No comments:

Post a Comment

back to top