sam
sam

Reputation: 2596

c# textbox data binding with date format

I have Textbox bounded from sql server database

column type is Date. so there is no time in that column

when binding data from database to this Textbox it shows date with time it is look like default time or something because it always has same value = 12:00:00

TB_Birthday.Text = dt.Rows[1][5].ToString();

First where that date comes from ? last How do I remove this time and show only date?

I am using .net4 with vs 2013

enter image description here

Upvotes: 1

Views: 1457

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

Since dt.Rows[1][5] returns object and we want apply a format we have to cast it to IFormattable interface:

 using System.Globalization;

 ...

 // "M/d/yyyy" - Month / Day / Year in this order; e.g. "9/14/2019"
 TB_Birthday.Text = (dt.Rows[1][5] as IFormattable)
   ?.ToString("M/d/yyyy", CultureInfo.CurrentCulture);

I've put ?.ToString() instead of .ToString() in order not throwing exception if dt.Rows[1][5] is null but propagte null to TB_Birthday.Text: TB_Birthday.Text will have an empty Text. In case of .net 4.0 vs 2013 (see comments below) we have to put

 TB_Birthday.Text = (dt.Rows[1][5] as IFormattable)
   ?.ToString("M/d/yyyy", CultureInfo.CurrentCulture);

Edit: Where time part comes from.

When we put

 TB_Birthday.Text = dt.Rows[1][5].ToString();

we read dt.Rows[1][5] which is boxed DateTime. DateTime structure has Date and Time parts. In your case Time part is all zeroes. However when you format with a help of .ToString() default format will be used which in your case includes Time part. So you have

 12:00:00 9/14/2019

All zeroes time is midnight (12:00:00 in 12 hour format)

Upvotes: 3

Related Questions