SahanaM-0755 avatar image
0 Votes"
SahanaM-0755 asked AlexLi-MSFT commented

How do i get back a listbox item after a window closes in C# WPF

I have 1 Listbox it takes items from TextBox, when an item is added to the listbox and the application is closed, upon opening the application the item added to the listbox will still be present.

Use case:

User opens application.
User adds item called "Item 1" to listbox using button.
User closes application.
User opens application again and sees that "Item 1" is still in the listbox, and the added item hasn't been lost by the application closing.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

PeterFleischer-3316 avatar image
0 Votes"
PeterFleischer-3316 answered PeterFleischer-3316 edited

Hi, try following demo. At first you must select typ of buffer to store items (lines). In demo I use ObservableCollection and txt file for saving items. In constructor I load the items (lines) and in destructor I save items (lines).


 <Window x:Class="Window010"
         Title="Window010" Height="450" Width="800">
     <TextBox Text="{Binding Text}" Margin="5"/>
     <Button Content="Add Item" Command="{Binding Cmd}" Margin="5"/>
     <ListBox ItemsSource="{Binding Col}" Margin="5"/>


 Imports System.Collections.ObjectModel
 Imports System.ComponentModel
 Imports System.IO
 Imports System.Runtime.CompilerServices
 Namespace WpfApp010
   Public Class ViewModel
     Implements IDisposable
     Private filePath As String = "c:\temp\xTest.txt"
     Public Sub New()
       If File.Exists(filePath) Then
         Col = New ObservableCollection(Of String)(File.ReadAllLines(filePath))
         Col = New ObservableCollection(Of String)
       End If
     End Sub
     Public Property Text As String
     Public Property Col As ObservableCollection(Of String)
     Public ReadOnly Property Cmd As ICommand = New RelayCommand(Sub(state)
                                                                 End Sub)
 #Region "IDisposable Support"
     Private disposedValue As Boolean 
     Protected Overridable Sub Dispose(disposing As Boolean)
       If Not disposedValue Then
         File.WriteAllLines(filePath, Col.ToArray)
       End If
       disposedValue = True
     End Sub
     Protected Overrides Sub Finalize()
     End Sub
     Public Sub Dispose() Implements IDisposable.Dispose
     End Sub
 #End Region
   End Class
   Public Class RelayCommand
     Implements ICommand
     Private ReadOnly _execute As Action(Of Object)
     Public Sub New(ByVal execute As Action(Of Object))
       Me._execute = execute
     End Sub
     Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
       Return True
     End Function
     Public Custom Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
       AddHandler(ByVal value As EventHandler)
         AddHandler CommandManager.RequerySuggested, value
       End AddHandler
       RemoveHandler(ByVal value As EventHandler)
         RemoveHandler CommandManager.RequerySuggested, value
       End RemoveHandler
       RaiseEvent(ByVal sender As Object, ByVal e As EventArgs)
       End RaiseEvent
     End Event
     Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
     End Sub
   End Class
 End Namespace

ViewModel in CSharp:

 using System;
 using System.Collections.ObjectModel;
 using System.IO;
 using System.Linq;
 using System.Windows;
 using System.Windows.Input;
 namespace WpfApp1
   namespace WpfApp010
     public class ViewModel : IDisposable
       private string filePath = @"c:\temp\xTest.txt";
       public ViewModel()
         if (File.Exists(filePath)) Col = new ObservableCollection<String>(File.ReadAllLines(filePath));
         else Col = new ObservableCollection<String>();
       public string Text { get; set; }
       public ObservableCollection<string> Col { get; set; }
       public ICommand Cmd { get => new RelayCommand((state) => Col.Add(Text)); }
       #region IDisposable Support
       private bool disposedValue;
       protected void Dispose(bool disposing)
         if (!disposedValue) File.WriteAllLines(filePath, Col.ToArray());
         disposedValue = true;
       ~ViewModel() => Dispose(false);
       public void Dispose() => Dispose(true);
     public class RelayCommand : ICommand
       private readonly Predicate<object> _canExecute;
       private readonly Action<object> _action;
       public RelayCommand(Action<object> action) : this(action, null) { }
       public RelayCommand(Action<object> action, Predicate<object> canExecute) { _action = action; _canExecute = canExecute; }
       public void Execute(object o) => _action(o);
       public bool CanExecute(object o) => _canExecute == null ? true : _canExecute(o);
       public event EventHandler CanExecuteChanged
         add { CommandManager.RequerySuggested += value; }
         remove { CommandManager.RequerySuggested -= value; }
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AlexLi-MSFT avatar image
0 Votes"
AlexLi-MSFT answered AlexLi-MSFT commented

Welcome to our Microsoft Q&A platform!

You can use ini file to remember ListBox Information:

  public partial class MainWindow : Window
         private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
         private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
         string iniFilePath = System.Environment.CurrentDirectory + @"\config.ini";
         string iniHead = "ListBoxInformation";
         string iniKey = "Key";
         string iniValue;
         StringBuilder temp;
         public MainWindow()
         private void Button_Click(object sender, RoutedEventArgs e)
             if (iniValue == null)
                 iniValue += temp;
             string str = textBox1.Text;
             if (!string.IsNullOrEmpty(str))
                 iniValue =  iniValue+","+str;
                 WritePrivateProfileString(iniHead, iniKey, iniValue, iniFilePath);              
         private void Window_Loaded(object sender, RoutedEventArgs e)
             temp = new StringBuilder(1024);
             GetPrivateProfileString(iniHead, iniKey, "", temp, 1024, iniFilePath);
             foreach (var item in temp.ToString().Split(new char[] { ',' }))
                 if(! string.IsNullOrEmpty(item))




1.gif (377.2 KiB)
· 4
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

I did same thing but it not working. after window opened listbox is empty it does not show previously entered items.

0 Votes 0 ·

After you closed the MainWindow,you can open the ini file to see if your Listboxitem is recorded in it.

before close window


after close window


0 Votes 0 ·

Listbox information is recording in Config.ini file, but recorded item is not showing in Listbox. Listbox become empty after closing Window.

0 Votes 0 ·
Show more comments