1

My code throws an error:

When converting string to datetime, parse the string to take the date before putting each variable into datetime object.

CODE:

I need to display default value in text box i.e. current date.

txtIssuingDate.Text = DateTime.Now.ToString("dd/MM/yyyy"); 

Then i need to save that in DB too without in specified format

ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text),  
    Convert.ToInt32(HiddenFieldComplaintID.Value),  
    txtLetterNo.Text,  
    txtDispatchNo.Text,  
    txtSubject.Text,  
    Convert.ToInt16(ddlDepartments.SelectedValue),  
    Convert.ToInt16(ddlDesignations.SelectedValue),  
    Convert.ToDateTime(txtIssuingDate.Text),  
    Convert.ToDateTime(txtDeadLine.Text));
DIF
  • 2,470
  • 6
  • 35
  • 49
user3518032
  • 423
  • 8
  • 25

2 Answers2

3

Use DateTime.Parse with CultureInfo.InvariantCulture in case that your culture doesn't use / as date-separator:

So instead of

Convert.ToDateTime(txtIssuingDate.Text)

which uses your current-culture's date-separator, this

DateTime.Parse(txtIssuingDate.Text, CultureInfo.InvariantCulture)

But then you should also do it when you assign the date to the TextBox.Text:

txtIssuingDate.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture);

The "/" Custom Format Specifier

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • @user3518032: it allows to ignore the current culture by using a fake-culture similar to `"en-US"`. This helps to prevent issues that are caused by number or date formatting. Read: http://stackoverflow.com/questions/2423377/what-is-the-invariant-culture – Tim Schmelter May 15 '14 at 15:08
1

try this

DateTime obj = DateTime.Now;
txtIssuingDate.Text = obj.ToString("dd/MM/yyyy");
ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text), Convert.ToInt32(HiddenFieldComplaintID.Value), txtLetterNo.Text, txtDispatchNo.Text, txtSubject.Text, Convert.ToInt16(ddlDepartments.SelectedValue), Convert.ToInt16(ddlDesignations.SelectedValue),
                obj, Convert.ToDateTime(txtDeadLine.Text));
Raju Padhara
  • 687
  • 1
  • 7
  • 20