I would like to puplate a list dynamically, and bind it to an asp repeater which use a custom control.
Here is my custom control (.acsx file) :
<%@ 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>
So I create a repeater in my aspx file :
<%@ 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>
List to populate repeater is declared :
Private Shared list_cars As ArrayList
On LoadPage event, I add one item in list :
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()
When I display page, I correctly see this :
this is a car
color = color of Me.m_car is (red)
OK, it works fine on load page event
But now, I want add item on button clic event defined here :
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
On click event, I see now that :
this is a car
color = (m_car Is Nothing)
this is a car
color = (m_car Is Nothing)
It doesn’t work, I think Container.DataItem is Nothing value, it is good instance only when loading page
I don’t know how to fix it, any help ?
On your Page_Load, use
Not Page.IsPostBackWhenever you click the button, a postback occurs and the list is overwritten with
list_cars = New ArrayList()in Page_Load.And also, asp.net is not windows application, you cannot add item to existing list because of the postback unless you hold the list in Session or ViewState
In your codebehind of your page add this property
To use this in your page: