Elgahir
Elgahir

Reputation: 57

Windows Phone C# Long List Selector

I am trying to add something from textblock but there's occurs a error that I can't handle with stackoverflow.

The code:

List<String> StringsList; 
private void Add_Click(object sender, RoutedEventArgs e)
{

    StringsList.Add(textBox.Text.ToString());
    longListSelector.ItemsSource = StringsList; 
}

That should be simple code that add from the list some string to the Long List selector. Could you please give me a tip or something? I was using the code from here:

https://code.msdn.microsoft.com/windowsapps/LongListSelector-Demo-45364cc9#content

This is the error:

$exception {System.NullReferenceException: Object reference not set to an instance of an object. at page3.Add_Click(Object sender, RoutedEventArgs e) at System.Windows.Controls.Primitives.ButtonBase.OnClick() at System.Windows.Controls.Button.OnClick() at System.Windows.Controls.Primitives.ButtonBase.b__3()} System.Exception {System.NullReferenceException}

Upvotes: 0

Views: 57

Answers (1)

Eldho
Eldho

Reputation: 8301

Instead of using List use ObservableCollection. Also make make sure its Public.

public ObservableCollection<String> StringsList { get; set; } 

    // Constructor 
    public MainPage() 
    { 
        InitializeComponent(); 

        StringsList = new ObservableCollection<string> { "First Text Item", "Second Text Item", "Third Text Item" }; 

        DataContext = StringsList; 
    } 

    private void Add_Click(object sender, RoutedEventArgs e) 
    { 
        StringsList.Add(textBox.Text); 
    } 

The ObservableCollection Represents a dynamic data collection that provides notifications when items get added, removed, or when the whole list is refreshed.

Please refer your attached sample carefully.

Upvotes: 1

Related Questions