Home > Back-end >  How to persist the selection of an item in a combo box between application restarts
How to persist the selection of an item in a combo box between application restarts

Time:08-17

In a WinForms application I am showing a list of all available audio devices in a combo box. I want the user to be able to select one of these items and for that selection to be persisted so that the next time the application is loaded the same device from combo box will selected by default.

How can I solve this?

Code to get list of available audio devices:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Form2 : Form
    {
        [DllImport("winmm.dll", SetLastError = true)]
        static extern uint waveInGetNumDevs();

        [DllImport("winmm.dll", SetLastError = true, CharSet = CharSet.Auto)]
        public static extern uint waveInGetDevCaps(uint hwo, ref WAVEOUTCAPS pwoc, uint cbwoc);

        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
        public struct WAVEOUTCAPS
        {
            public ushort wMid;
            public ushort wPid;
            public uint vDriverVersion;
            [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 64)]
            public string szPname;
            public uint dwFormats;
            public ushort wChannels;
            public ushort wReserved1;
            public uint dwSupport;
        }

        public void FillSoundDevicesInCombobox()
        {
            uint devices = waveInGetNumDevs();
            WAVEOUTCAPS caps = new WAVEOUTCAPS();
            for (uint i = 0; i < devices; i  )
            {
                waveInGetDevCaps(i, ref caps, (uint)Marshal.SizeOf(caps));
                CB1.Items.Add(caps.szPname);
            }

        }
        public Form2()
        {
            InitializeComponent();
        }

        private void Form2_Load(object sender, EventArgs e)
        {
            FillSoundDevicesInCombobox();

        }

private void button1_Click(object sender, EventArgs e)
        {
           
    }
    }
}

My expectation is that when the user clicks on the button the selected item will be saved. Then if I restart the application, the same device should be re-selected when the form loads.

CodePudding user response:

I'll ignore the microphone issue and instead address the real underlying issue:

How to persist the selection of an item in a combo box between application restarts

The easiest way to do this in a WinForms application is to use the Application Settings:

Create setting at design time

Once your setting has been defined we can use it in the code. In this scenario I am NOT storing the index, instead I will use the actual value. This was if in a future execution the values loaded for the microphones is different or in a different sequence, the code will still select the correct microphone, or none at all.

We can access the Application Settings through the Properties.Settings.Default namespace:

private void Form2_Load(object sender, EventArgs e)
{
    FillSoundDevicesInCombobox();

    // Only select the device if there is a value to load
    if (!String.IsNullOrWhiteSpace(Properties.Settings.Default.SelectedAudioDevice))
    {
        // find the device, matching on the value, not index
        var item = CB1.Items.Cast<string>().FirstOrDefault(x => x.Equals(Properties.Settings.Default.SelectedAudioDevice));
        // only select the device if we found one that matched the previous selection.
        if (item != null)
            CB1.SelectedItem = item;
    }
}

Then in the button click, we can store the current selection:

How To: Write User Settings at Run Time with C#
Settings that are application-scoped are read-only, and can only be changed at design time or by altering the .config file in between application sessions. Settings that are user-scoped, however, can be written at run time just as you would change any property value. The new value persists for the duration of the application session. You can persist the changes to the settings between application sessions by calling the Save method.

private void button1_Click(object sender, EventArgs e)
{
    // persist the changes to the user scoped settings store
    Properties.Settings.Default.SelectedAudioDevice = CB1.SelectedItem?.ToString();
    Properties.Settings.Default.Save();
}
  • Related