Formatting a date in a gridview with auto-generated fields

B

BillE

I am populating a gridview using auto-generated fields, because I need to
enable sorting.

I would like to format a column containing dates in the gridview.

How is this done?

Thanks
Bill
 
G

Guest

Hi there Billie,

you have to handle RowDataBound event


-- aspx page --

<asp:GridView runat="server" ID="gridView"
AutoGenerateColumns="true"
OnRowDataBound="gridView_RowDataBound">

-- end aspx page --


-- code beside --

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;

int index = GetDateColumnIndex(row);

e.Row.Cells[index].Text = ((DateTime)
row[index]).ToString("dd/MM/yyyyyyyy-MM-dd");
}
}

private int dateColumnIndex = -1;
private int GetDateColumnIndex(DataRow row)
{
if (this.dateColumnIndex == -1)
{
this.dateColumnIndex =
row.Table.Columns.IndexOf("ItemRecieved");

if (dateColumnIndex < 0)
{
throw new Exception(
"datasource does not contain the MyDateColumn column");
}
}
return this.dateColumnIndex;
}

-- end code beside --


Hope this helps
 
B

BillE

Thank you kindly.

Milosz Skalecki said:
Hi there Billie,

you have to handle RowDataBound event


-- aspx page --

<asp:GridView runat="server" ID="gridView"
AutoGenerateColumns="true"
OnRowDataBound="gridView_RowDataBound">

-- end aspx page --


-- code beside --

protected void gridView_RowDataBound(object sender, GridViewRowEventArgs
e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRow row = ((DataRowView)e.Row.DataItem).Row;

int index = GetDateColumnIndex(row);

e.Row.Cells[index].Text = ((DateTime)
row[index]).ToString("dd/MM/yyyyyyyy-MM-dd");
}
}

private int dateColumnIndex = -1;
private int GetDateColumnIndex(DataRow row)
{
if (this.dateColumnIndex == -1)
{
this.dateColumnIndex =
row.Table.Columns.IndexOf("ItemRecieved");

if (dateColumnIndex < 0)
{
throw new Exception(
"datasource does not contain the MyDateColumn column");
}
}
return this.dateColumnIndex;
}

-- end code beside --


Hope this helps

--
Milosz


BillE said:
I am populating a gridview using auto-generated fields, because I need to
enable sorting.

I would like to format a column containing dates in the gridview.

How is this done?

Thanks
Bill
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,020
Latest member
GenesisGai

Latest Threads

Top