locked
generic list, add, and same values RRS feed

  • Question

  • User1335416789 posted
    Hi, 
    I have a problem with adding of items to generic list,
    problem is when I insert 1. item to the list, everithing is ok, but if I insert second item, first and second has same values. 

    code looks like that (asp.net 4.0):
     
    Partial Class _Default 
    Inherits System.Web.UI.Page 
    
    <Serializable()> 
    Public Class Product 
    Shared Property Material As String 
    Shared Property Type As String 
    Shared Property ImageURL As String 
    End Class 
    
    Public Property CurrentSelection() As Product 
    Get 
    Dim text As Product = ViewState("Product") 
    If text IsNot Nothing Then 
    Return text 
    Else 
    Dim Ntext As New Product 
    ViewState("Product") = Ntext 
    Return Ntext 
    End If 
    End Get 
    Set(ByVal value As Product) 
    ViewState("Product") = value 
    End Set 
    End Property 
    
    Public Property Products() As List(Of Product) 
    Get 
    Dim text As List(Of Product) = ViewState("Products") 
    If text IsNot Nothing Then 
    Return text 
    Else 
    Dim Ntext As New List(Of Product) 
    ViewState("Products") = Ntext 
    Return Ntext 
    End If 
    End Get 
    Set(ByVal value As List(Of Product)) 
    ViewState("Products") = value 
    End Set 
    End Property 
    
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click 
    Dim First As New Product 
    First.Material = "111" 
    First.Type = "" 
    First.ImageURL = "" 
    Dim Second As New Product 
    Second.Material = "2222" 
    Second.Type = "" 
    Second.ImageURL = "" 
    Products.Add(First) 
    Products.Add(Second) 
    
    For Each item In Products 
    Response.Write(First.Material & "</br>") 
    Next 
    End Sub 
    
    End Class


    thanks for ideas


     

    Monday, January 17, 2011 7:26 AM

Answers

  • User-1952482173 posted

    Your code should be OK. But, the way you printed out was wrong. You only print the First when you do Response.Write(First.Material). You should have used item instead.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, January 17, 2011 10:25 AM