I'm hoping to dynamically change the number of columns in my ItemTemplate of my ListView:
<asp:ListView runat="server" ID="ReportListView" DataSourceID="ReportListViewSDS">
<LayoutTemplate>
<table>
<tr>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder" />
</tr>
</table>
</LayoutTemplate>
<ItemTemplate>
<!-- need to dynamically create the number of columns in the code behind
based on the select statement in the SelectCommand -->
</ItemTemplate>
</asp:ListView>
Then in the code behind I've got:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Based on The Request.Form variables sent, the SQL command will
' select x number of columns:
' SqlStatement = "SELECT " for each Request.Form values " FROM staff"
' example: "SELECT Fname, Lname, email, phone FROM staff"
' Run sql command.
' that all works, the question now is how do i change the ItemTemplate
' so that it has the correct number of columns. Something like this: (pseudo code)
For each row found in sql command
ReportListView.ItemTemplate.Add( "<tr>" )
For each Request.Form as i
ReportLIstView.ItemTemplate.Add( "<td>" & sqlresult(i) & "</td>" )
Next
ReportListView.ItemTemplate.Add( "</tr>" )
Next
End Sub
Maybe there's another way to go about it, but that's the only idea of got so far. asp.net newbie, any advise, very welcome! Thanks!
Using a combination of the answers I recieved this is what I got to work:
<asp:ListView runat="server" ID="ReportListView" DataSourceID="ReportListViewSDS">
<ItemTemplate>
<table>
<tr>
<asp:PlaceHolder runat="server" ID="itemPlaceHolder" />
</tr>
</table>
</ItemTemplate>
</asp:ListView>
Code Behind:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
' Based on The Request.Form variables sent, the SQL command will
' select x number of columns:
' SqlStatement = "SELECT " for each Request.Form values " FROM staff"
' example: "SELECT Fname, Lname, email, phone FROM staff"
' Run sql command.
' this seems to actually run the sql, and bind the results. If i don't run the function DataBind(), it's as if the sql never runs.
ReportListView.DataBind()
' the rest of the work is done in the next function.
End Sub
Protected Sub ReportListView_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewItemEventArgs) Handles ReportListView.ItemDataBound
If (e.Item.ItemType = ListViewItemType.DataItem) Then
Dim plc As PlaceHolder = DirectCast(e.Item.FindControl("itemPlaceHolder"), PlaceHolder)
Dim di As Data.DataRowView = e.Item.DataItem()
For Each c In di.Row.ItemArray
Dim l As New Literal
l.Text = String.Format("<td class='customreport'>{0}</td>", c.ToString)
plc.Controls.Add(l)
Next
End If
End Sub
Thanks much for the direction of the other 2 answers, that definately got me 90%, just a couple other tweaks and i was good to go. Thanks!