I am having trouble with databinding when trying to add it to a dropdownlist. I can get it to work with a label:

<asp:Label ID="Label3" runat="server" Text='<%# Eval("Location") %>'></asp:Label>

But when I try with the DropDownList I get this error and I can't seem to find an answer for it.

Databinding expressions are only supported on objects that have a DataBinding event. System.Web.UI.WebControls.ListItem does not have a DataBinding event.

Here is the code I use:

<asp:DropDownList ID="ddlLocation1" runat="server">
    <asp:ListItem Text='<%# Eval("Location") %>' Value='<%# Eval("TotalCost") %>' />
</asp:DropDownList> 

Any help would be greatly appreciated.

Dani AI

Generated

— the problem is a markup-binding limitation: putting a <%# %> expression inside a static ListItem won’t be evaluated because ListItem is not a markup target for data-binding the way a Label or other server controls are. ’s pointer to the ASP.NET area was on target; the simplest fixes are to bind the DropDownList itself (use DataSource/DataTextField/DataValueField) or build the items in code-behind.

A straightforward, robust approach in Page_Load (VB) is:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        Dim dt = GetLocations() ' DataTable or IEnumerable(Of T) with Location and TotalCost
        ddlLocation1.DataSource = dt
        ddlLocation1.DataTextField = "Location"
        ddlLocation1.DataValueField = "TotalCost"
        ddlLocation1.DataBind()
    End If
End Sub

If you prefer to add items programmatically (for more control), iterate the data and create ListItem objects:

For Each r As DataRow In dt.Rows
    ddlLocation1.Items.Add(New ListItem(r("Location").ToString(), r("TotalCost").ToString()))
Next

Notes and quick troubleshooting

  • If you mix static ListItems with data-bound items, set AppendDataBoundItems="true" on the DropDownList so binding won’t wipe out static entries.
  • Always bind only when Not IsPostBack unless you intentionally need to rebind every request (rebinding can clear selections).
  • Confirm the field/property names used in DataTextField/DataValueField exactly match your data source.
  • If the DropDownList is inside a templated control (GridView/Repeater), bind the DropDownList in the template’s ItemDataBound handler instead of using <%# %> inside a ListItem.

These approaches avoid placing Eval expressions inside a static ListItem and will resolve the error you’re seeing.

I guess if u post this in ASP.net u might get some help....

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.