Binding time values to asp.net GridView - asp.net

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

Related

Fixed DataStringFormat GirdView

Is there a way how to format a number in gridview with fixed currency format? I use
DataFormatString="{0:C}"
but since my page is available in multiple languages it also changes currency signs. Is there a way how to apply format to column like this?
"C0",CultureInfo.CreateSpecificCulture('en-US')
Yes, change the data format by transform when get the data, no when show them. If you parse the data to string in the format that you want you don't need to transform in the server. For example if you are using sql server you can format by the view.
If this is noy what you expect write me in a comment.
Thanks
You can overwrite the Culture for that page and even define a custom currency symbol if needed.
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US")
{
NumberFormat = { CurrencySymbol = "%" }
};
For those who will need something similar there is a solution
protected void grdReport_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
Decimal dec;
if (Decimal.TryParse(e.Row.Cells[1].Text, out dec))
e.Row.Cells[1].Text = dec.ToString("C0", CultureInfo.CreateSpecificCulture("cs-CZ"));
}
I need only display those number so this is ok for me. In case you need to work with them you need to split the text and then convert it to number.

GridView date/time column conditional formatting

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.

Adobe Flex date

Hi I am having a problem in date.
I am having a custom dateChooser.
In the dateChooser component highlights some holidays and at the same time lists the holidays in a container.
The Problem is the date I am displaying in the container is not in ascending order could some one please help.
Link for the demo application with view source enabled
http://125.22.254.206/clients/flexdemos/calendardemo/calendardemo.html
The said logic is implemented in ExtendedDateChooser.as under custome folder.
Are you trying to sort the date in the 'holidayView' vbox?
You cant compare and sort two dates. You can use the date comparison method given below (search the web to find a better one).If the control in the vbox to display holidays is a datagrid, using
<mx:DataGridColumn
headerText="Created Date"
date="createdDt"
sortCompareFunction="date_sortCompareFunc">
</mx:DataGridColumn>
in the tag attribute will result in sortedDate
private function date_sortCompareFunc(itemA:Object, itemB:Object):int
{
/* Date.parse() returns an int, but
ObjectUtil.dateCompare() expects two
Date objects, so convert String to
int to Date. */
var dateA:Date=isoToDate(itemA.createdDt);
var dateB:Date=isoToDate(itemB.createdDt);
return ObjectUtil.dateCompare(dateB, dateA);
}
private function isoToDate(value:String):Date {
var dateStr:String = value;
dateStr = dateStr.replace(/\-/g, "/");
dateStr = dateStr.replace("T", " ");
dateStr = dateStr.replace("Z", " GMT-0000");
return new Date(Date.parse(dateStr));
}
I think, you cant sort by Date.
First, I can't see the container in your app.
My way would be to parse the date in to milliseconds since 1970
parse(date:String):Number
Then you can sort it by some logic.
BR
Frank

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