views:

2185

answers:

5

Hi , I am reading data from an excel sheet and displaying it in a data gridview.There are some date columns in the excel.So when i read the data from the excel and bind it to the dataGridView.The date is displayed in the format "02/02/2009 12:00:00 AM" but the actual data in the excel column is in the format "2/2/2009".So how to change the date format in the datagridview.

Since i am binding the data from the dataset i dont have any template columns or bound column set so i dont know where to set the HtmlEncode="False" DataFormatString = "{0:T}"

Is there any way to do this.Please help me.

Please find the below code sample.

string OleDbConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= "+ FileUpload1.PostedFile.FileName + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=1\"";

string strSheetName = "Sheet1";
OleDbConnection oledbConnection;
OleDbCommand oledbCommand;
OleDbDataAdapter oledbAdapter;

oledbCommand = new OleDbCommand();
oledbAdapter = new OleDbDataAdapter();
DataSet dsExcellData = new DataSet();

oledbConnection = new OleDbConnection(OleDbConnection);
oledbConnection.Open();
oledbCommand.Connection = oledbConnection;


oledbCommand.CommandText = "Select * from [" + strSheetName + "$]"; // i want to find this sheet name
oledbAdapter.SelectCommand = oledbCommand;
oledbAdapter.Fill(dsExcellData);

oledbConnection.Close();

GridView1.DataSource = dsExcellData.Tables[0];

GridView1.DataBind();

========================================================== I tried the

dsExcellData.Tables[0].Rows[rowcount]["date_column"].ToString()] = dsExcellData.Tables[0].Rows[rowcount]["date_column"].ToString()].ToString("d");

but the value is not getting assigned as "mm/dd/yyyy" It is also taking the time default time again (mm/dd/yyyy hh:mm:ss AM).

=============================================================

I am just assigning the data set to the gridview.The problem is the dataset is reading the date column in the format mm/dd/yyyy hh:mm:ss AM.I am unable to change the data in the dataset also.

=============================================================

Finaly i got the answer from ScottE:

we have to add the below code in the itemdatabound of the datagridview :

protected void dgValidatedData_ItemDataBound1(object sender, DataGridItemEventArgs e)
{

        for (int i = 0; i <= e.Item.Cells.Count - 1; i++)
        {
            System.DateTime cellDate = default(System.DateTime);
            if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate))
            {
                e.Item.Cells[i].Text = string.Format("{0:d}", cellDate);
            }
        }

}
A: 

Date format you should define in your GridView column. For example:


<asp:GridView>
...
<asp:TemplateField>
 <ItemTemplate>
   <asp:Label ID="Label1" runat="server" Text='<%# Eval("Date", "{0:T}") %>'></asp:Label>
  </ItemTemplate>
...
</asp:GridView>
Tadas
I am not using any item template . since i am binding the data dynamically..I will be knowing the column name of the column name which i will retrieve from database.Thanks for your post.
Jebli
+2  A: 

If you're binding it as a asp:BoundField you'll need to set htmlencode to false.

<asp:BoundField HtmlEncode="false" DataField="Blah" DataFormatString="{0:d}" />
ScottE
I am not using asp bound field.I am just binding the data to the datagrid from a dataset. Thanks for your response.
Jebli
+2  A: 

Ok, try this, where "Item" is the column name (could be multiple) that is a date that needs formatting. This is of course vb.net, but you can sort that out. I'm sure there's a better way, but this works.

Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        For i As Integer = 0 To e.Row.Cells.Count - 1
            If gv.HeaderRow.Cells(i).Text = "Item" Then
                e.Row.Cells(i).Text = String.Format("{0:d}", CType(e.Row.Cells(i).Text, Date))
            End If
        Next
    End If
End Sub

Or, if you don't know what columns will have dates, the following will work as well:

Protected Sub gv_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        For i As Integer = 0 To e.Row.Cells.Count - 1
            Dim cellDate As Date
            If Date.TryParse(e.Row.Cells(i).Text, cellDate) Then
                e.Row.Cells(i).Text = String.Format("{0:d}", cellDate)
            End If
        Next
    End If
End Sub
ScottE
Hi you are the man.Thanks the code is working .I am using a gridview and please find the code in C# : protected void dgValidatedData_ItemDataBound1(object sender, DataGridItemEventArgs e) { for (int i = 0; i <= e.Item.Cells.Count - 1; i++) { System.DateTime cellDate = default(System.DateTime); if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate)) { e.Item.Cells[i].Text = string.Format("{0:d}", cellDate); } } }}Thank you soo much
Jebli
No problem. If it works for you, mark it as correct - there are too many unanswered questions in here already!
ScottE
A: 

Here is a solution using a custom control that derives from GridView:

using System;
using System.Collections;
using System.Web.UI.WebControls;

namespace CustomControls {

  public class FormattedGridView : GridView {

    protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource) {

      // Call base method and return the collection as an ArrayList
      var columns = (ArrayList) base.CreateColumns(dataSource, useDataSource);

      for (var i = 0; i < columns.Count; i++) {

        var agf = columns[i] as AutoGeneratedField;

        if (agf != null && agf.DataType == typeof(DateTime)) {

          // create a new column because the AutoGeneratedField does not support
          // the modification of the DataFormatString property
          var bf = new BoundField();

          // copy some of the original properties
          bf.DataField = agf.DataField;
          bf.HeaderText = agf.HeaderText;
          bf.HtmlEncode = false;

          // set the format for the DateTime types
          bf.DataFormatString = "{0:T}";

          // replace the existing auto-generated colums
          columns[i] = bf;
        }

      }

      return columns;
    }
  }

}
Julien Poulin
Hi sorry to mention i was not using C# 3.5.I am using C# 2.0
Jebli
A: 

Finaly i got the answer from ScottE:

we have to add the below code in the itemdatabound of the datagridview :

protected void dg_ItemDataBound1(object sender, DataGridItemEventArgs e) {

    for (int i = 0; i <= e.Item.Cells.Count - 1; i++)
    {
        System.DateTime cellDate = default(System.DateTime);
        if (System.DateTime.TryParse(e.Item.Cells[i].Text, out cellDate))
        {
            e.Item.Cells[i].Text = string.Format("{0:d}", cellDate);
        }
    }

}

But the above code will check all the data that is bound to the datagrig.It will try to parse the data as datetime in the cell.If it is a valid datetime then it will convert the data into the format which we applied.

Jebli