What's the deal with databinder.eval and container.dataitem?

xiaoxiao2021-04-02  234

The DataBinding Expression

<% # Some Expression%>

Is Evaluated In The Language of The Page (VB, C #, ETC.) This Can Have A Big Impact on The Current Syntax, So Be Very Careful When You Are Looking at Docs for the language you are for.

Container.DataItem is a runtime alias for the DataItem for this specific item in the bound list. For a grid which displays 10 rows of data, this is one row from the datasource. The actual type of DataItem is determined by the type of the datasource . for example, if the datasource is a Dataview, the type of DataItem is DataRowView. If the type of the datasource is an array of strings, the type of DataItem is String. If the datasource is a collection of strongly-typed objects (for Example "Employees" Objects ", The Type of DataItem is Employees.

Each of these cases requires a slightly different databinding expression, with further differences between VB and C #. In every case, you want the databinding expression to produce a string that can be displayed in the page.

Here Are Some Examples:

Array of strings:

VB / C # <% # Container.DataItem%>

Field from DataView:

VB <% # Container.DataItem ("Employeename")%>

C # <% # ((DATAROWVIEW) Container.DataItem) ["Employeename"]%>

Property from a Collection of Objects:

VB <% # Container.DataItem.customername%>

C # <% # (Customer) Container.DataItem) .customername%>

Non-String Property from a Collection of Objects:

VB <% # cstr (container.dataitem.customerid)%>

C # <% # ((Customer) Container.DataItem) .customerid.toString ()%>

As you can see the syntax is tricky, especially for C #, which requires explicit casting. So we've provided a DataBinder.Eval () helper method that figures out the syntax for you and formats the result as a string. It's really convenient, with a couple of caveats: it's late bound (uses reflection at runtime to figure out the data types), and it only supports basic data types in the fields: string, int, datetime, etc.DataBinder.Eval takes 2 or 3 arguments. The first arg is the data object to bind to. In the case of DataGrid, DataList and Repeater, Container.DataItem is the single row. The second arg the string name of the field from the data object you which to display. DataBinder.Eval Uses these Two Pieces of Information To Work Out The Rest of The Expression Syntax.

An Optional Third Argument IS A. Net Formatting String. DataBinder.eval Will Handle A Single Replacement for {0} ONLY. SO The Example Below:

>

Wrapping DataBinder.Eval in CStr () is unnecessary as the compiler will wrap the statement with a Convert.ToString like this: control1.SetDataBoundString (0, Convert.ToString (DataBinder.Eval (item1.DataItem, "ID")));

Best of all, the databinder.eval syntax is the same for vb and c #.

Susan Warren11 / 30/2000 1:48:00 PM


New Post(0)