0

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}

Draken
  • 3,134
  • 13
  • 34
  • 54
Elgahir
  • 57
  • 2
  • 8
  • Oh sorry, 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} – Elgahir Nov 05 '17 at 13:10
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Federico Dipuma Nov 05 '17 at 13:15

1 Answers1

1

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.

Eldho
  • 7,795
  • 5
  • 40
  • 77