简体   繁体   中英

ASP.NET Listbox inside of gridview

I have a listbox inside of a gridview which appears when you click edit, it has a list of event types which you can select multiple. I cannot figure out how to update my entity when the update button is clicked. I need to be able to update the entity collection with the selection made from the listbox inside the gridview. The gridview is using an entity datasource. Below is the list box in the gridview.

   <asp:TemplateField HeaderText="Event Type">
            <ItemTemplate>
                <asp:Label runat="server" ID="eventTypeLabel" Text="<%#VenueExplorer.Utilities.StringUtils.convertEventsToCommaString(Container.DataItem) %>" />
            </ItemTemplate>
            <EditItemTemplate>
                <asp:ListBox ID="eventListbox" runat="server" DataSourceID="eventTypeDataSource" DataValueField="EventTypeID" DataTextField="EventType" SelectionMode="Multiple"></asp:ListBox>
            </EditItemTemplate>
        </asp:TemplateField>

Is there a way I can update the entity binded to the gridview before the actual save is performed?

During the RowUpdating event of your GridView , you can capture the ListBox 's selected values.

Without knowing your full markup or database structure, I can only mock up the intended code. Something like this, though you'll obviously have to modify it to suit your needs:

protected void grdView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
    ListBox eventListbox = (ListBox)grdViewName.Rows[e.RowIndex].Cells[ZeroBasedCellNumberOfTheListBox].FindControl("eventListbox");

    // Retrieve the currently selected entity (row) from the database
    ParentEntity yourParentEntity = from entity in DataContext.ParentEntity where entity.ID == grdViewName.Rows[e.RowIndex].Cells[IndexOfYourEntitysID].Text;

    foreach (ListItem item in eventListbox.Items)
    {
        if (item.Selected)
        {
            EventType eventType = new EventType();
            eventType.ID = item.Value;
            eventType.Name = item.Text;

            yourParentEntity.EventTypes.Add(eventType);            }
    }

    DataContext.Commit();

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM