How to Use DateTime Picker and Save in Database in Window Form

Step 1: Form

Drag and down a Datetime Picker from ToolBox. and go its property and set "Custom Format" as"yyyy-mm-dd", and other property "Format" as "custom".

ToolBox

Step 2: Code

code

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel;  
  4. using System.Data;  
  5. using System.Drawing;  
  6. using System.Text;  
  7. using System.Windows.Forms;  
  8. using System.Data.SqlClient;  
  9. namespace First_Csharp_app  
  10. {  
  11.       public partial class Form1 : Form  
  12.       {  
  13.             public Form1()  
  14.             {  
  15.                   InitializeComponent();  
  16.             }  
  17.             String gender; //we have to define this  
  18.             private void button1_Click(object sender, EventArgs e)  
  19.             {  
  20.                   SqlConnection con = new SqlConnection(str);  
  21.                   String str = "server=MUNESH-PC;database=windowapp;UID=sa;password=123";  
  22.                   String query = "insert into data (E.id,name,surname,age,gender,DOB) values ('"+this.eid_txt.tex                  t+"','"+this.nametxt.text+"','"+this.surname_txt.text+"','"+this.age_txt.text+"' , '"+this.gend                  er+"' , '"+this.DateTimePicker1.Text+"')";  
  23.                   SqlCommand cmd = new sqComamnd(query,con); SqlDataReader dbr;  

  24.                   try{con.open();  
  25.                   {
  26.                         dbr = cmd.ExecuteReader();MessageBox.Show("saved");while(dbr.read()){}  
  27.                   }  
  28.                   catch (Exception es)  
  29.                   {  
  30.                         MessageBox.Show(es.Message);  
  31.                   }  
  32.             }  

  33.             private void rediobutton1.checked(object sender, EventArgs e)  
  34.             {  
  35.                   gender = "male";  
  36.             }  
  37.             private void rediobutton1.checked(object sender, EventArgs e)  
  38.             {  
  39.                   gender = "female";  
  40.             }  
  41.       }  
  42. }  
Step 3: Output

Run your application:

saved

you can go on my Blog_Munesh
Ebook Download
View all
Learn
View all