5
Reply

How to pass Null for DataTime Value

Marcus Dutton

Marcus Dutton

Dec 19 2015 5:40 AM
335
Here is my code.
 
Sometimes the dob field will be empty or null, as it not a required field.
 
how can I re-write this to accept this.
 
private void btnSave_Click(object sender, EventArgs e)
{
Employee svEmp = new Employee();
svEmp.FullName1 = tbxFullName.Text;
svEmp.ShortName1 = tbxShortName.Text;
svEmp.Title1 = cbxTitle.Text;
svEmp.DateOfBirth1 = Convert.ToDateTime(mtbxDoB.Text);
svEmp.Type1 = cbxType.Text;
svEmp.Active1 = cbxActive.Text;
svEmp.OfficePhone1 = cbxOfficePhone.Text;
svEmp.HomePhone1 = mtbHomePhone.Text;
svEmp.MobilePhone1 = mtbMobilePhone.Text;
svEmp.EmergContact1 = tbxEmergContact.Text;
svEmp.EmergPhone1 = mtbContactPhone.Text;
int result = dbconnect.Insert(svEmp);
if (result > 0)
{
Timer timer1 = new Timer();
timer1.Interval = 5000;
statusAction.Text = ("Update Successful!");
timer1.Start();
timer1.Tick += new EventHandler(timer1_Tick);
}
else
{
Timer timer1 = new Timer();
timer1.Interval = 5000;
statusAction.Text = ("Update Failed!");
timer1.Start();
timer1.Tick += new EventHandler(timer1_Tick);
}
}
here is the other end of that method which is in a different class file.

 //employee save method    
     public int Insert(Employee svEmp)         {             int result = 0;             try             {                 dbcommand.CommandText = "INSERT INTO tblEmployee(FullName, ShortName, Title, OfficePhone, HomePhone, MobilePhone, DateOfBirth, Type, Active,EmergPhone, EmergContact) VALUES (@vFull, @vShort, @vTitle, @vOffice, @vHome, @vMobile, @vDob, @vType, @vActive, @vEPhone, @vEContact)";                 dbcommand.Parameters.AddWithValue("@vFull", svEmp.FullName1);                 dbcommand.Parameters.AddWithValue("@vShort", svEmp.ShortName1);                 dbcommand.Parameters.AddWithValue("@vTitle", svEmp.Title1);                 dbcommand.Parameters.AddWithValue("@vOffice", svEmp.OfficePhone1);                 dbcommand.Parameters.AddWithValue("@vHome", svEmp.HomePhone1);                 dbcommand.Parameters.AddWithValue("@vMobile", svEmp.MobilePhone1);                 dbcommand.Parameters.AddWithValue("@vDob", svEmp.DateOfBirth1);                 dbcommand.Parameters.AddWithValue("@vType", svEmp.Type1);                 dbcommand.Parameters.AddWithValue("@vActive", svEmp.Active1);                 dbcommand.Parameters.AddWithValue("@vEPhone", svEmp.EmergPhone1);                 dbcommand.Parameters.AddWithValue("@vEContact", svEmp.EmergContact1);                 dbcommand.CommandType = System.Data.CommandType.Text;                 dbconnect.Open();                 result = dbcommand.ExecuteNonQuery();             }             catch (Exception ex)             {                 System.Windows.Forms.MessageBox.Show(ex.Message);             }             finally             {                 dbconnect.Close();                 dbconnect.Dispose();             }             return result;         }

 

Answers (5)