What is the difference between binding data in data grid view methods? - asp.net

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

Related

"The name 'Bind' does not exist in the current context" when manipulating the result of Bind

I'm trying to bind a hue value retrieved from a databound gridview control to the backcolour of the text box that is being used to display the value. After editing the ItemTemplate for the relevant column, I've added the following code to take the Hue value from my data, convert it to a colour and then pass that to the BackColor property:
<asp:TextBox ID="TextBox8" runat="server" BackColor='<%# GetColourFromHue(int.Parse(Bind("Hue"))) %>' ReadOnly="True" Text='<%# Bind("Hue") %>'></asp:TextBox>
However, I get the following error:
CS0103: The name 'Bind' does not exist in the current context
The issue is the fact that I'm wrapping the Bind("Hue") command in more code: GetColourFromHue(int.Parse(Bind("Hue"))).
How can I manipulate the value returned by Bind so that I can assign it to the control property?
Thanks to #Andrei's comment, I can't use Bind, but I can use Eval. The following works:
GetColourFromHue(int.Parse(Eval("Hue").ToString()))

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.

w3c validation error in asp.net

I am new in W3c validations, I am trying to fix this error but it's not happening. The error is following:
character "&" is the first character of a delimiter but occurred as data.
I am using DataList Control to bind data and here is the line where the w3c validation error occurs.
<asp:Label ID="lblDescription"
runat="server"
Text='<%#Eval("Decr") %>'>
</asp:Label>
In database, the Decr is stored and this(&) special character is also given in the description field. w3c is not validating this line.
& is a special charater for concat, you need to escape it: make them all & not &.
Here is the solution I came up with:
<asp:Label ID="lblDescription" runat="server" Text='<%# Server.HtmlEncode( (string) Eval("Decr")) %>'></asp:Label>

how to format date time at time of binding in gridview

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}")%>

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