Доступ к элементу ListView itemtemplate из codebehind
Я надеюсь динамически изменить количество столбцов в моей ItemTemplate моего 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>
Тогда в коде позади меня есть:
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
Может быть, есть другой способ сделать это, но это единственная идея got до сих пор. asp.net новичок, любой совет, очень приветствуется! Спасибо!
4 ответов:
Я думаю, что вам придется сделать это немного по-другому. Попробуйте что-нибудь вроде этого:
<table> <asp:ListView ID="ListView1" runat="server"> <ItemTemplate> <tr> <asp:PlaceHolder Id="PlaceHolder1" runat="server" /> </tr> </ItemTemplate> </asp:ListView> </table>Синтаксис может быть не идеальным, но попробуйте сделать что-то подобное в своем коде:
For Each listItem As ListViewDataItem In ListView1.Items Dim plc As PlaceHolder = DirectCast(listItem.FindControl("PlaceHolder1"), PlaceHolder) If plc IsNot Nothing Then For Each item As String In Request.Form plc.Controls.Add(New Literal(String.Format("<td>{0}</td>", item))) Next End If Next
Другим способом было бы настроить ItemTemplate таким же образом, но так как вы используете элемент управления databound, вы можете воспользоваться событием DataBound listview. Этот синтаксис может быть не идеальным, потому что вы можете использовать другую коллекцию для привязки к списку (что будет сделано после выполнения запроса), но это должно привести вас на правильный путь:
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 di As Data.DataRowView = e.Item.DataItem Dim plc As PlaceHolder = DirectCast(e.Item.FindControl("PlaceHolder1"), PlaceHolder) For Each c In di.Row.ItemArray Dim l As New Literal l.Text = String.Format("<td>{0}</td>", c.ToString) plc.Controls.Add(l) Next End If End SubЯ обычно использую ретранслятор для этого типа работы, так как он голый и легкий. Вы действительно вы не пользуетесь ни одной из функций listview из того, что я вижу.
Используя комбинацию ответов, которые я получил, вот что я получил для работы:
<asp:ListView runat="server" ID="ReportListView" DataSourceID="ReportListViewSDS"> <ItemTemplate> <table> <tr> <asp:PlaceHolder runat="server" ID="itemPlaceHolder" /> </tr> </table> </ItemTemplate> </asp:ListView>Код Сзади:
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Большое Спасибо за направление других 2 ответов, которые определенно дали мне 90%, просто пару других настроек, и я был хорош, чтобы пойти. Спасибо!
Я использую этот код, чтобы скрыть элемент в шаблоне элемента
visible='<%# Eval("Abstract").ToString().Length == 0 ? false : true %>'
Comments