question

SahanaM-0755 avatar image
0 Votes"
SahanaM-0755 asked ·

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.

windows-wpf
10 |1000 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 ·

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).

XAML:

 <Window x:Class="Window010"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:local="clr-namespace:WpfApp1.WpfApp010"
         mc:Ignorable="d"
         Title="Window010" Height="450" Width="800">
   <Window.DataContext>
     <local:ViewModel/>
   </Window.DataContext>
     <StackPanel>
     <TextBox Text="{Binding Text}" Margin="5"/>
     <Button Content="Add Item" Command="{Binding Cmd}" Margin="5"/>
     <ListBox ItemsSource="{Binding Col}" Margin="5"/>
   </StackPanel>
 </Window>

Code:

 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))
       Else
         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)
                                                                   Col.Add(Text)
                                                                 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()
       Dispose(False)
       MyBase.Finalize()
     End Sub
     Public Sub Dispose() Implements IDisposable.Dispose
       Dispose(True)
     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
       Me._execute(parameter)
     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);
       #endregion
     }
     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; }
       }
     }
   }
 }
· Share
10 |1000 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 ·

Welcome to our Microsoft Q&A platform!

You can use ini file to remember ListBox Information:

  public partial class MainWindow : Window
     {
         [DllImport("kernel32")]
         private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
         [DllImport("kernel32")]
         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()
         {
             InitializeComponent();
         }
    
         private void Button_Click(object sender, RoutedEventArgs e)
         {
             if (iniValue == null)
             {
                 iniValue += temp;
             }
             string str = textBox1.Text;
             if (!string.IsNullOrEmpty(str))
             {
                 iniValue =  iniValue+","+str;
                 listBox1.Items.Add(textBox1.Text);
                 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))
                 listBox1.Items.Add(item);
             }
         }
     }

7616-annotation-2020-04-23-102727.png


7595-1.gif



Thanks.


1.gif (377.2 KiB)
· 4 · Share
10 |1000 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.

Hii,
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

7751-annotation-2020-04-28-092535.png


after close window

7761-annotation-2020-04-28-092727.png


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