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.

you need to databind the DropDownList itself, as you point out correctly the ListItem doesn't have any data binding events.

<asp:DropDownList ID="ddlLocation1" runat="server" DataSourceID="dsLocation" DataValueField="TotalCost" DataTextField="Location" />

Sorry I don't quite get what you mean. I'll add my full code.

VB:

Private Sub generate_Event2()

        'Populate_Referral

        DGSearch2.AllowPaging = True
        Dim ds As DataSet = New DataSet
        Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        Dim myCommand As SqlDataAdapter = New SqlDataAdapter("Admin_Populate_Workshop1", myConnection)
        ' Mark the Command as a SPROC
        myCommand.SelectCommand.CommandType = CommandType.StoredProcedure

        '@RegID as varchar(50),
        Session("UserID") = "Admin"
        '----------------------------------------
        Dim parameterRegId As SqlParameter = New SqlParameter("@RegId", SqlDbType.VarChar, 50)
        parameterRegId.Value = Session("UserId")
        myCommand.SelectCommand.Parameters.Add(parameterRegId)


        Try

            myConnection.Open()

            myCommand.Fill(ds, "User_Info")

            If ds.Tables(0).Rows.Count = 0 Then
                Me.pnlBindGrid2.Visible = True
                lblNoRows2.Visible = True
                'Me.BtnPrint.Visible = False
            Else
                Me.pnlBindGrid2.Visible = True
                'Session("Interest") = Me.DDLDiscipline.SelectedItem.Text
                'Session("Area") = Me.LstSubDiscipline.SelectedItem.Text
                ' Me.BtnPrint.Visible = True
                lblNoRows2.Visible = False
            End If

            DGSearch2.DataSource = ds
            DGSearch2.DataBind()
            'DropDownList1.DataSource = ddlValues;
            'DropDownList1.DataBind();


            myConnection.Close()

        Catch e As SqlException
            Response.Write(e.Message)
        End Try


    End Sub

    Protected Sub Grid_Change2(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs)

        DGSearch2.PageIndex = e.NewPageIndex
        'Rebind the data. 
        generate_Event2()

    End Sub

asp.net:

<asp:Panel  CssClass = "searchResultsTable" ID="pnlBindGrid2" runat="server" Visible="False" Width="100%">
        <center>
            <asp:GridView ID="DGSearch2" runat="server" AllowPaging="True" 
                AutoGenerateColumns="False" DataKeyNames="RefNo" 
                OnPageIndexChanging="Grid_Change2" Width="95%" Font-Names="Calibri" 
                Font-Size="12pt" RowStyle-HorizontalAlign ="Left" GridLines="None" 
                PageSize="10000" ShowHeader="False" >

                <AlternatingRowStyle BorderStyle="None" />

                <Columns>

                    <asp:TemplateField>
                      <ItemTemplate>

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

                      </ItemTemplate>                 
                        <ItemStyle Width="48%" />
                    </asp:TemplateField> 

                    <asp:BoundField DataField="Ref_No" Visible="False" HeaderText="RefNo" />
                    <asp:BoundField DataField="Rowguid" HeaderText="Rowguid" Visible="False" />

                </Columns>                

            </asp:GridView> 
            </center>
            <center>

            <table id="Table2" border="0" cellpadding="0" cellspacing="0" class="defaulttext" width="95%">
                <tr>
                    <td align="center" style="height: 17px"><center>
                        <asp:Label ID="lblNoRows2" runat="server" CssClass="defaulttext" ForeColor="Red" Visible="False" Width="162px" Font-Names="Calibri" Font-Size="11pt">No workshops in database</asp:Label></center></td>
                </tr>
                <tr>
                    <td align="center" style="height: 17px">
                    </td>
                </tr>

            </table>
            </center> 
        </asp:Panel>

ah, ok... your dropdown is inside a gridview, which I assume means you have a list of Locations the user can select from, and the parent records will display the selected Location they have been saved with. (hopefully that makes sense).

If so, this is going to be a 2 stage process:
1 - bind the dropdown to the list of items (which will be its own query/dataset, and databound as I described above)
2 - bind the selected item to the current record in the gridview.

Ok so I've got the drop down list working but I currently have 3 entries in the database and it's only showing the 2nd and 3rd entry in the drop down list. No matter how many entries I have it doesn't show the first one. Here's the code:

Private Sub generate_DDL()

        'Dim Ref_No As String

        'Me.ddlInterestArea.Items.Clear()

        Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.AppSettings("ConnectionString"))
        Dim myCommand As SqlCommand = New SqlCommand("Admin_Populate_Workshop1", myConnection)

        ' Mark the Command as a SPROC
        myCommand.CommandType = CommandType.StoredProcedure
        ' Add Parameters to SPROC

        Dim parameterRegId As SqlParameter = New SqlParameter("@RegId", SqlDbType.VarChar, 20)
        parameterRegId.Value = Session("UserID")
        myCommand.Parameters.Add(parameterRegId)


        myConnection.Open()

        Dim myReader As SqlDataReader
        myReader = myCommand.ExecuteReader
        ' Always call Read before accessing data.
        If myReader.Read Then


            'Set up the data binding.
            ddlLocation.DataSource = myReader
            ddlLocation.DataTextField = "Town"
            ddlLocation.DataValueField = "TotalCost"
            ddlLocation.DataBind()




        Else

            'Response.Redirect("login-new.aspx")

        End If
        ' always call Close when done reading.
        myReader.Close()

        ' Close the connection when done with it.
        myConnection.Close()

        ddlLocation.Items.Insert(0, "Select Location")



    End Sub

I have tried removing the 2nd last line "ddlLocation.Items.Insert(0, "Select Location") which creates the first entry for the drop down list, but nothing changes

Disregard that last post. Ive got it working now :)

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.