0

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?

MusicLovingIndianGirl
  • 5,909
  • 9
  • 34
  • 65

3 Answers3

0

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.

Community
  • 1
  • 1
walther
  • 13,466
  • 5
  • 41
  • 67
  • Can you give me an example please? – MusicLovingIndianGirl Apr 15 '13 at 08:12
  • Say, I choose a value from the dropdown which I have in a popup window. When I click add button, I need to populate that value to the grid's row. How do I do that? – MusicLovingIndianGirl Apr 15 '13 at 08:24
  • @Aishvarya, that's a completely separate question! :) You need to create an event handler for the click event and in this you'd have to set the `DataSource` of your GridView and called the method `.DataBind()` on it. DataSource should take the data from some external method returning a collection inheriting from IEnumerable containing items that have this getter property I've shown you. In your GridView simply reference the `DateIn24HourFormat` property and it should give you correct output. If you want to continue a debate about databinding, create probably a separate question. – walther Apr 15 '13 at 08:30
0

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");
    }
  }
Sachin
  • 40,216
  • 7
  • 90
  • 102
0

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

vijay
  • 1,323
  • 1
  • 11
  • 15
  • Say, I choose a value from the dropdown which I have in a popup window. When I click add button, I need to populate that value to the grid's row. How do I do that? – MusicLovingIndianGirl Apr 15 '13 at 08:22