0

我想动态创建一个列表,并将其绑定到使用自定义控件的 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

在点击事件中,我现在看到:

这是一辆车

颜色 = (m_car 什么都不是)

这是一辆车

颜色 = (m_car 什么都不是)

它不起作用,我认为 Container.DataItem 没有什么价值,只有在加载页面时它才是好实例

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

4

1 回答 1

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

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

而且,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
于 2012-11-23T13:48:39.777 回答