GridView date/time column conditional formatting - asp.net

I have a GridView with a DateTime column. My dates may not have a time part. Using DataFormatString="{0:MM/dd/yyyy hh:mm tt}" will write 12:00 AM when no time was entered. Is there a way to avoid this? That is, if the date has a time setted, then show it, otherwise show just the date?

If there is no special restriction, than from server side you can convert the date time to string and return the required data and on grid side just tell the grid that it is a string value.

You can't use a conditional with a format string; you have to add an event handler to the GridView's ItemDataBound event, and format it yourself:
void Grid_ItemDataBound(object sender, GridItemEventArgs e)
{
var date = e.Item[<index>].Text;
if (date.EndsWith(" 12:00 AM"))
e.Item[<index>].Text = date.Replace(" 12:00 AM", "");
}
Something like that.

Related

Binding time values to asp.net GridView

I need to bind time values to my gridview. For example, if the time is 13:00, I need to display it as 13-00 in the grid. But it displays as 01-00. How do I resolve this?
You can use GridView.RowDataBound Event to achieve it. Format your time string as you want and assign to to the grid view cell.
You can use date formats to convert datetime into 24-hrs format.
void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[1].Text = DateTime.Now.ToString("MM/dd/yyyy HH:mm");
}
}
You need to convert the value into 24-hour format (for instance by selecting a different culture for your application) or simply create some converter class that will convert this for you. There are multiple resources to learn from.
Something like this should work:
DateTime localTime = DateTime.Now;
// 24 hour format -- use 'H' or 'HH'
string timeString24Hour = localTime.ToString("HH:mm", CultureInfo.CurrentCulture);
Taken from another answer here in SO Convert AM/PM time to 24 hours format?
If your culture uses 12-hour format, use a different culture info for the parsing that supports 24-hour format.
Of course you'd probably like to wrap this in a getter property so it will be available for the binding
public string DateIn24HourFormat
{
get
{
return MyConvertFunction(this.Time);
}
}
You get the idea.
Give your Time format in DataFormatString property in BoundColumn.
Apply format as
{0:HH-mm}
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring.aspx

Convert string date to system datetime in C#

I want to convert string date to system datetime in C#. The user enters date through textbox and it should be converted as to datetime. I trid following code but its not working...
DateTime ToDate = Convert.ToDateTime(txtToDate.Text);
DateTime FromDate = DateTime.Parse(txtFromDate.Text);
It shows the following exception
"String was not recognized as a valid DateTime."
How to do this...???
You could use DateTime.ParseExact(). That way you can specify the format of the input string, so it will be parsed correctly, for example:
dateString = "Sun 15 Jun 2008";
format = "ddd dd MMM yyyy";
try
{
DateTime result = DateTime.ParseExact(dateString, format, CultureInfo.CurrentCulture);
}
catch (FormatException)
{
}
whatever user enters in your textbox that should be in valid date format, otherwise write your own function to make it in valid format. then Convert it into DateTime format .
for different format you can check this :
http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
for more help you can check similar question on this site :
Validate a DateTime in C#
You can of course parse the user's input and rely on the users to always enter a correct date. But I'd recommend to use a specific control for entering a date, such as the calendar control of the ajax control toolkit.
By using such a control, you can prevent invalid input and it's also much easier for the user. If you search for DatePicker or similar, I'm sure you can find lot's of other similar controls.
Ask the user to enter his datetime in a particular format into textbox i.e., either "ddMMyyyyhhmmss" or "dd/MM/yyyy hh:mm:ss tt" or "dd-MM-yyyy hh:mm:ss tt" or some other formats and use the help of following code to convert in to a Valid datetime.
DateTime ToDate = DateTime.ParseExact(txtToDate.Text, <User DateTime format as String>,
System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
Instead, if the above coding makes complicated then you can try DateTime.TryParse() also
First of all you have to validate text box value that it is valid or not, you can use ajax MaskeditExtender control for that and restrict the use enter only require date formate.
DateTime dt = Convert.ToDateTime(date);
here date is in string.

Custom format integer as date in DataGrid

I have an integer field in my database that contains a date value in the form yyyyMMdd. Is it possible to parse this as a date in the form dd/MM/yyyy as bound to a datagrid?
Currently the field is bound like this:
<asp:boundcolumn datafield="access_date" headertext="Last logged on"></asp:boundcolumn>
Why don't you use Date for dates in database ?
You can convert int to datetime using following sample code:
var sdate = intdate.ToString();
var date = DateTime.ParseExact(sdate, "yyy/MM/dd", CultureInfo.InvariantCulture);
Thanks to gor for guiding me through this.
His answer in itself was not the entire solution, but after some commenting back and forth, I ended up with a good solution.
Instead of using a asp:boundcolumn in the grid, I had to use asp:templatecolumn and display it through a binding expression (like gor explained in his comment, although I think he based his answer on using the asp:listview control, while I use the old asp:datagrid control).
In the <columns> collection of the asp:datagrid control:
<asp:TemplateColumn headertext="Last logged on" >
<ItemTemplate><%#DateStringFromInt(Eval("access_date"))%></ItemTemplate>
</asp:TemplateColumn>
In the code-behind:
protected string DateStringFromInt(object value)
{
DateTime date;
if (DateTime.TryParseExact(value.ToString(), "yyyyMMdd",
CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal,
out date))
{
return date.ToString("dd/MM/yyyy");
}
return value.ToString(); //Return original if not expected format
}

date validation

can any one tell me the code to validate the date field in signup form(which shd also validate the leap year and no of days in each month
That depends on the input but suppose you have a string input for the whole date then you could try something like:
try
{
DateTime parsedDate = DateTime.Parse(incomingDateString);
}
catch
{
throw new Exception("Incoming Date string could not be parsed as a DateTime");
}
Alternatively if you have three integers as strings coming in from the form then you would replace the DateTime.Parse with
DateTime parsedDate = new DateTime(Int32.Parse(yearString), Int32.Parse(MonthString), Int32.Parse(DayString));
and allow the DateTime constructor take care of the details of analyzing days of month and leap years. You could be more sophisticated and use Int32.TryParse and provide more specific error messages and checks for null strings if thats what you need.
You can make sure you get a valid date by adding a calendar control or a date picker control. This will avoid having to add extra validation just to validate this field.
If you don't want to use a calendar control or date picker, you can use DateTime.Parse and place it inside a Try, Catch block.
dateString = YourDateField.Text;
try {
dateValue = DateTime.Parse(dateString);
}
catch (FormatException) {
Console.WriteLine("Unable to convert, this is not a valid date '{0}'.", dateString);
}
Hope this helps.

System.Web.UI.WebControls.Calendar is it possible to change the color of individual selections?

I have code to do multiple selections in a calendar control but I would like to change the color of the initially selected day to green and the end date to red. Visually this would indicate the start date and end date of a certain service to be
provided. Should I be looking into RenderControl Method for my calander or more looking into setting some attribute of the days in the control?
The multiple select code is attributable to
Steve Wellins
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
System.Web.UI.WebControls.Calendar TheCalendar = sender as System.Web.UI.WebControls.Calendar;
// create new list of dates or get stored list of dates
List SelectedDates;
if (ViewState["SelectedDates"] == null)
SelectedDates = new List();
else
SelectedDates = ViewState["SelectedDates"] as List;
// if date is already in list, remove it, otherwise, add it
if (SelectedDates.Contains(TheCalendar.SelectedDate) == false)
SelectedDates.Add(Calendar1.SelectedDate);
else
SelectedDates.Remove(Calendar1.SelectedDate);
// set the calendar to our list of dates
TheCalendar.SelectedDates.Clear();
foreach (DateTime Date in SelectedDates)
TheCalendar.SelectedDates.Add(Date);
// store list for next postback
ViewState["SelectedDates"] = SelectedDates;
}
This code may overwrite any date or formatting applied to the calendar but I am not above saving and restoring this formating to the calendar.
foreach (DateTime Date in SelectedDates)
TheCalendar.SelectedDates.Add(Date);
I am glad to research leads if you point me down the right path or terms to search for.
From the MSDN site the Calendar..::.OnDayRender Method is invoked while each day is being rendered. I am a .NET noob... how to use it all?

Resources