I’ve got a DetailsView which has some static fields defined in my markup and adds some extra fields dynamically in the VB codebehind. It should be noted that the DetailsView lives in an UpdatePanel.
Assume that I would like to get inventory information for a number of warehouses, but I only want to see those which have stock on hand. In addition I have some static information such as product, sku, etc.
The problem I was having was that every time I clicked the “Details” button it would just keep appending the dynamic fields to the end and never re-rendering the table. I figure I either need a conditional or to tell it to re-render somehow. I suspect this problem arises from my use of the UpdatePanel but it’s important for the user experience of my customer to keep this.
'Warehouse Stock by Location
Dim stockDT As New DataTable
For Each row As DataRow In stockDT.Rows 'Add column for each Warehouse that has stock
'Adds the fields to the DetailsView dynamically for Warehouses with stock.
Dim col As New DataColumn(WarehouseLocID + row(WarehouseLocID).ToString)
Dim bf As New BoundField
bf.HeaderText = "Warehouse " + row(WarehouseLocID)
bf.DataField = col.ColumnName
'NEED HELP HERE! HOW TO UPDATE OR RE-CREATE THE DETAILSVIEW TO REFLECT NEW INFO?
If Not SAPDetailsView.HasControls Then 'BROKEN
SAPDetailsView.Fields.Add(bf)
Else
SAPDetailsView.Fields.Item(0).HeaderText = bf.DataField 'UPDATES THE WRONG "ITEM" FIELD VALUE!!
End If
Next
Here’s the very basic markup.
<asp:UpdatePanel ID="statusUpdatePanel" runat="server">
<ContentTemplate>
<asp:GridView ID="ProductsTable" DataSourceID="ProductsSDS">
<Columns>
<asp:ButtonField ButtonType="Button" Text="Details" CommandName="Select" />
</Columns>
</asp:GridView>
<asp:DetailsView ID="WarehouseStock" runat="server" AutoGenerateRows="False">
<Fields>
<asp:BoundField HeaderText="Product" DataField="Product" />
<asp:BoundField HeaderText="Unit Price" DataField="UnitPrice" />
<asp:BoundField HeaderText="SKU" DataField="SKU" />
</Fields>
</asp:DetailsView>
<!-- The Dynamic Fields are appended in the codebehind -->
</ContentTemplate>
</asp:UpdatePanel>
Based on your logic, my guess is that you are not clearing SAPDetailsView prior to updating it with new data. Also note that dynamically added fields usually need to be added in the page_init event in order to survive postback.
If you are just sending the fields to the user and not expecting any data back, then this won’t matter, but you also won’t get any fields posted back.