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);
}
}
}