Link to home
Create AccountLog in
Avatar of nkhelashvili
nkhelashvili

asked on

Add calculated field to GridView

I have following  fields in the table:  

ID  int  ,
DateStart DateTime.
DateEnd   DateTime


I want  to add calculated field besides these fields  in GridView in asp.net but not by adding calculated field
to my table and not by adding calculated column in sql query.

I want to format that field using C#  syntax like this:   DateStart.ToShortDateString() + " - "   DateEnd.ToShortDateString()




Avatar of sybe
sybe

> and not by adding calculated column in sql query

Why not? That would be the easiest, wouldn't it?

SELECT id, datestart, dateend, convert(char(10), datestart, 101) + '-' + convert(char(10), dateend, 101) AS starttoend FROM yourtable
Use <asp:template> field
Avatar of nkhelashvili

ASKER

sybe,

I don`t won`t to do it, because I`m using globalization in my application...

lotusnotesnewbie

Can you be more specific, how to do in my case?


<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="calulatedDate">
<%# Eval("DateStart") %>
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>

Convert the column to date in Eval statement
> because I`m using globalization in my application..

You mean you want a specified dateformat returned from the database? Look here: http://howto.redcomputer.net/sql/select_datetime_format.php
ASKER CERTIFIED SOLUTION
Avatar of nkhelashvili
nkhelashvili

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
I`ve found solution myself and I have to close question. Here is solution:

I`ve overrided  RowDataBound  event of GridView and formatted fields as I wanted:
protected void GDVDates_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex < 0) return;  // when e.Row.RowIndex is -1, it`s HeaderText
        e.Row.Cells[3].Text = Convert.ToDateTime(e.Row.Cells[1].Text).ToShortDateString() + " - " + Convert.ToDateTime(e.Row.Cells[1].Text).ToShortDateString();
        e.Row.Cells[1].Text = Convert.ToDateTime(e.Row.Cells[1].Text).ToShortDateString();
        e.Row.Cells[2].Text = Convert.ToDateTime(e.Row.Cells[2].Text).ToShortDateString();
    }

Open in new window

Posted incorrectly, code must be:



protected void GDVDates_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowIndex < 0) return;  // when e.Row.RowIndex is -1, it`s HeaderText
        e.Row.Cells[3].Text = Convert.ToDateTime(e.Row.Cells[1].Text).ToShortDateString() + " - " + Convert.ToDateTime(e.Row.Cells[2].Text).ToShortDateString();
        e.Row.Cells[1].Text = Convert.ToDateTime(e.Row.Cells[1].Text).ToShortDateString();
        e.Row.Cells[2].Text = Convert.ToDateTime(e.Row.Cells[2].Text).ToShortDateString();
    }

Open in new window