ASP vb.net:如何动态更改绑定到转发器的列表

时间:2012-11-23 13:38:27

标签: asp.net vb.net dynamic repeater itemtemplate

我想动态地填充列表,并将其绑定到使用自定义控件的asp转发器。

这是我的自定义控件(.acsx文件):

<%@ Control Language="VB" ClassName="ControlCar" %>
<script runat="server">
    Private m_car As Car = Nothing
    Public Property Car() As Car
        Get
            Car= m_car
        End Get
        Set(ByVal value As Car)
            m_car = value
        End Set
    End Property

    Protected Sub Panel_OnLoad(ByVal sender As Object, ByVal e As System.EventArgs)
        If Me.m_car Is Nothing Then
            lit_color.Text = "(m_car Is Nothing)"
        Else
            lit_color.Text = "color of Me.m_car is (" & Me.m_car.Color & ")"
        End If
    End Sub

</script>

<asp:Panel ID="panel" OnLoad="Panel_OnLoad" runat="server">
    this is a car<br />
    color = <asp:Literal ID="lit_color" runat="server"></asp:Literal><br />
    <br />
</asp:Panel>

所以我在我的aspx文件中创建了一个转发器:

<%@ Register TagPrefix="uc" TagName="ControlCar" Src="myfile.ascx" %>
<asp:Repeater ID="id_repeater" runat="server">
    <headertemplate>
    </headertemplate>
    <itemtemplate>  
    <uc:ControlCar id="ControlCarTemplate" Car=<%# CType(Container.DataItem, Car)%> runat="server" />
    </itemtemplate>
</asp:Repeater>    

声明填充转发器的列表:

Private Shared list_cars As ArrayList

在LoadPage事件中,我在列表中添加了一个项目:

If IsPostBack Then
    Return
End If

list_cars = New ArrayList()
Dim car As Car = New Car
car.Color = "red"
list_cars .Add(car)
id_repeater.DataSource = list_cars 
id_repeater.DataBind()

当我显示页面时,我正确地看到了这一点:

  

这是一辆车

     

color = Me.m_car的颜色是(红色)

好的,它在加载页面事件

上正常工作

但是现在,我想在这里定义的按钮clic事件上添加项目:

Sub OnClickAdd(ByVal sender As Object, ByVal e As System.EventArgs)
    Dim car = New Car
    car.Color = "blue"
    list_cars.Add(car)
    id_repeater_products.DataSource = list_cars
    id_repeater_products.DataBind()
End Sub

点击事件,我现在看到:

  

这是一辆车

     

color =(m_car Is Nothing)

     

这是一辆车

     

color =(m_car Is Nothing)

它不起作用,我认为Container.DataItem是Nothing值,只有在加载页面时才是好例子

我不知道如何解决它,有什么帮助吗?

1 个答案:

答案 0 :(得分:0)

在Page_Load上,使用Not Page.IsPostBack

If Not Page.IsPostBack Then

    list_cars = New ArrayList()
    Dim car As Car = New Car
    car.Color = "red"
    list_cars .Add(car)
    id_repeater.DataSource = list_cars 
    id_repeater.DataBind()

End If

每当您点击该按钮时,都会发生回发,并在Page_Load中使用list_cars = New ArrayList()覆盖该列表。

而且,asp.net不是Windows应用程序,你不能因为回发而将项目添加到现有列表,除非你在Session或ViewState中保存列表

在您的网页代码隐藏中添加此属性

Public Property list_cars As ArrayList

    Get
       If ViewState("list_cars") IsNot Nothing Then
          Dim list As ArrayList = CType(ViewState("list_cars"), ArrayList)
          return list
       End If

       return Nothing 'or return an empty list
    End Get

    Set
         ViewState("list_cars") = value
    End Set

End Property

要在您的页面中使用此功能:

Dim updatedList As ArrayList = list_cars
updatedList.Add(car)

list_cars = updatedList