Sam Cogan
Sam Cogan

Reputation: 4334

Add controls dynamically to a listview

I have an asp.net listview. The data that populates it is sorted into groups, and i'm using some code in the listview item template, that essentially checks if the grouping field has changed in the data, and if so it prints a new row, with the heading, so it looks a bit like this:

<ItemTemplate>
<%# AddGroupingRowIfWPHasChanged() %>

    <tr id="row" class="GridViewRow" runat="server" >
    <td valign="top" align="left"  ><%# Eval("item1") %></td>
.......
</itemTemplate>

This works great. However now I need to add a button the the group heading field, and I can't seem to get this to work. Obvioulsy this button only needs adding if the heading has changed, but the AddGroupingRowIfWPHasChanged() method does not seem to have access to the current ListviewItem, so I can't add a control.

Any suggestions on how I can add a control to a list view dynamically, depandant on whether its a group heading or not?

Upvotes: 0

Views: 2735

Answers (4)

Ryan
Ryan

Reputation: 655

Create a UserControl to include in place of the AddGroupingRowIfWPHasChanged() method call. Override Render(). Use the logic that's currently in AddGroupingRowIfWPHasChanged() to render the control if the group has changed; otherwise, render an empty string.

Upvotes: 0

Ryan
Ryan

Reputation: 655

Try using the GroupTemplate and GroupSeparatorTemplate instead of trying to fit it all in the ItemTemplate.

Upvotes: 0

Ian Jacobs
Ian Jacobs

Reputation: 5501

It may be easier to override the ItemInserting event in the codebehind and do it from there

Upvotes: 1

Kyle B.
Kyle B.

Reputation: 5787

Use a placeholder?

.aspx

<asp:Placeholder id="plhControlHolder" runat="server" />

code-behind

' ** use FindControl if instead a databound event, otherwise you could skip.
Dim plcControlHolder as PlaceHolder = e.Row.FindControl("plcControlHolder") 
Dim btnDynamic As New Button
btnDynamic.Id = "MyButton"
plcControlHolder.Controls.Add(btnDynamic)

Upvotes: 1

Related Questions