how to format date time at time of binding in gridview - asp.net

I have a field of type DateTime which is bound in gridview.
Now, i would liketo display only date from this field, and not time.
Date Should be in 1/1/0001 this format.
I am using DotnetNuke
My code is as follows
<asp:TemplateField HeaderText="Created On">
<itemtemplate>
<%#DataBinder.Eval(Container.DataItem, "Alb_Created_Date","0:dd/MM/yyyy}")%>
</itemtemplate>
</asp:TemplateField>`.
I have tried the format that is used but its output is like this 1/1/0001 12:00:00 AM.
What shall I do?

You are missing an opening angular brace {. Try this.
<asp:TemplateField HeaderText="Created On">
<itemtemplate>
<%# DataBinder.Eval(Container.DataItem, "Alb_Created_Date", "{0:dd/MM/yyyy}")%>
</itemtemplate>
</asp:TemplateField>

In your code you have given wrong syntax in the format, and due to which its not formatting correctly and giving out the data base value itself. Please, format it as below.
<%#DataBinder.Eval(Container.DataItem, "Alb_Created_Date","{0:dd/MM/yyyy}")%>

Related

Display Local Time in GridView

I have an asp.net gridview bound to the following sql server 2008r2 data source:
<asp:SqlDataSource ID="dsFault" runat="server" DataSourceMode="DataSet"
ConnectionString="<%$ ConnectionStrings:ESBExceptionDb %>"
SelectCommand="select * from Fault order by datetime desc"></asp:SqlDataSource>
In my Fault table there is a column called DateTime of type datetime. The values stored in this column are in UTC format and I need them to be displayed in the local timezone for the browser
I have added a template field to the Columns collection of the grid view as follows:
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblLocalTime" runat="server"
Text='<%# String.Format("{0:f}", Eval("DateTime").ToLocalTime()) %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
When I browse the page I get the following error:
CS1061: 'object' does not contain a definition for 'ToLocalTime' and no
extension method 'ToLocalTime' accepting a first argument of type 'object'
could be found (are you missing a using directive or an assembly reference?)
Can anyone please tell me where I've gone wrong?
Thanks, Rob.
The Eval("DateTime") Value that returns from your database is not a C# DataTime object.
and because the function .ToLocalTime() belongs to the DateTime c# object you can't use it.
You need to convert the object to string and then use the function .ToLocalTime()
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblLocalTime" runat="server"
Text='<%# Convert.ToDateTime(Eval("DateTime")).ToLocalTime() %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Ones you converted it to DateTime Object, you can use any format available
For Example
Text='<%# Convert.ToDateTime(Eval("DateTime")).ToString("dd/MM/yyyy") %>'
In addition to the other answers, remember that ToLocalTime() will return the SERVER local time not the browser local time as you requested.
Try like this
<%# Eval("DateTime", "{0:T}")%>
<asp:Label ID="lblLocalTime" runat="server"
Text='<%# Eval("DateTime", "{0:T}")%>'>
</asp:Label>
This will do the trick! Give this a try.
<asp:TemplateField HeaderText="Account Created">
<ItemTemplate>
<asp:Label ID="lblLocalTime" runat="server"
Text='<%# Convert.ToDateTime(Eval("CreateDate", "{0:g}")).ToLocalTime() %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It looks like there is no clean and simple way to do this, strange!!. The answer's mentioned so far try to convert the date to server timezone, not to client/browser's. i.e if the server is in USA and client in India, you won't see the datetime in indian timezone, it will be in USA's.
A duplicate of this has better answers. Basically, you either have to do one of below -
Send client timezone information to the server and do approp conversion there. It is better to send the timezone name rather than timezone offset as timezone offset can differ based on DST. You can use Intl.DateTimeFormat().resolvedOptions().timeZone to send the timezone name.
Send UTC date strings to
the client and let it do the conversion using javascript(new
Date(ISOUTCDateString)). This is what happens in WCF.

how to validate MaskedEditExtender control for MM/dd/yyyy format?

I am using maskedEditExtender control for getting date..
Code inside MaskedEditExtender is
cc1:MaskedEditExtender ID="MaskedEditExtender1" runat="server" TargetControlID="ui_txtRequestDateTime" ClearMaskOnLostFocus="false" Mask="99/99/9999 99:99" UserTimeFormat ="TwentyFourHour">
I need DateTime in MM/dd/yyyy hh:mm formate ,If i use calenderExtender control i can use Format="MM/dd/yyyy" ,but here i couldt specify the format MM/dd/yyyy, its generally "99/99/9999 99:99" format, the 1st two 9's for month, how to tell to user that they have to give month only, if i give value above 12, like 23,24 its showing exception..
Please give some idea..
Use RegularExpression validator with your textbox as follows:
<asp:TextBox ID="txtDate" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="valRegDate" ValidationGroup="OrderAdd"
ControlToValidate="txtDate" runat="server" ErrorMessage="Please provide a valid date."
ForeColor="Red" ValidationExpression="^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$"></asp:RegularExpressionValidator>

What is the difference between binding data in data grid view methods?

What is the difference between binding data in data grid view methods ??
<ItemTemplate>
<asp:LinkButton ID="lnkBtnUserName" runat="server"
Text='<%# DataBinder.Eval(Container.DataItem,"UserFirstName")%>'
CommandArgument='<%# Eval("UserID") %>' OnClick="lnkBtnUserName_Click" />
</ItemTemplate>
and this second one
<asp:TemplateField HeaderText="Employee ID">
<ItemTemplate>
<asp:Label ID="lblempid" runat="server" Text='<%# Bind("EmpId.EmpId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
means in
method 1
Text='<%# DataBinder.Eval(Container.DataItem,"UserFirstName")%>'
CommandArgument='<%# Eval("UserID") %>'
method 2
Text='<%# Bind("EmpId.EmpId")
also explain use one this CommandArgument='<%# Eval("UserID") in 1st one ????
Call such as Eval("UserID") corresponds to TemplateControl.Eval method call and that itself actually translates into call such as DataBinder.Eval(GetDataItem(), "UserID"). In summary, Eval is shorthand syntax for DataBinder.Eval - that internally inspects first argument and based on its type, it will try to resolve the second argument over it - for example, for data row, it will try to resolve to a column name while for plain objects, it will use reflection to resolve to property name.
Bind is special syntax that results into bi-directional binding used when editing i.e. control will get value from data source (similar to Eval) and it will also update (modified) value back to data source. AFAIK, Bind does not correspond to a method call (as Eval) but instead ASP.NET compiler would spit the necessary code to ensure two way data binding.
See data binding expressions overview: http://msdn.microsoft.com/en-us/library/ms178366.aspx

I need CompareValidator control to accept date in format month/day/year

I have the following template defined within DetailsView ( DetailsView is bound to object data source ):
<EditItemTemplate>
<asp:TextBox ID="txtReleaseDate" runat="server"
Text='<%# Bind("ReleaseDate", "{0:d}") %>'>
</asp:TextBox>
<asp:CompareValidator ID="valReleaseDateType" runat="server"
ControlToValidate="txtReleaseDate" Type="Date" Operator="DataTypeCheck"
Display="Dynamic" > *
</asp:CompareValidator>
</EditItemTemplate>
Assuming I enter into TextBox txtReleaseDate a date in format month/day/year, then upon clicking an Update or Insert button, a CompareValidator control complains that date format is not valid. But if I enter date in format day/month/year, then object data source throws an exception Cannot convert value of parameter 'releaseDate' from 'System.String' to 'System.DateTime', while CompareValidator doesn’t complain.
I need the two controls to accept the same date format, so:
a) Since my DB stores date in format day/month/year, the best option would be for ODS to also accept this as valid date format. Can ODS be configured that way?
b)Can CompareValidator be configured to also accept month/day/year format?
thanx
Probably you can set the CurrentUICulture of thread to en-GB format.
Try setting the web.config Globalization
I think
format is "dd/MM/yyyy"
try putting "eb-US" one.
Gud luck.

what is the use of Eval() in asp.net

What is the use of Eval() in ASP.NET?
While binding a databound control, you can evaluate a field of the row in your data source with eval() function.
For example you can add a column to your gridview like that :
<asp:BoundField DataField="YourFieldName" />
And alternatively, this is the way with eval :
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lbl" runat="server" Text='<%# Eval("YourFieldName") %>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
It seems a little bit complex, but it's flexible, because you can set any property of the control with the eval() function :
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl='<%# "ShowDetails.aspx?id="+Eval("Id") %>'
Text='<%# Eval("Text", "{0}") %>'></asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Eval is used to bind to an UI item that is setup to be read-only (eg: a label or a read-only text box), i.e., Eval is used for one way binding - for reading from a database into a UI field.
It is generally used for late-bound data (not known from start) and usually bound to the smallest part of the data-bound control that contains a whole record. The Eval method takes the name of a data field and returns a string containing the value of that field from the current record in the data source. You can supply an optional second parameter to specify a format for the returned string. The string format parameter uses the syntax defined for the Format method of the String class.
IrishChieftain didn't really address the question, so here's my take:
eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

Resources