0

I want to set the last selected item from a combobox as its default, meaning when I close this form and reopen it, the combobox shows and selects the last selected item again.

I have tried to save the SelectedIndex as an INT and use it like this:

public Form1()
{
    InitializeComponent();
    combobox1.SelectedIndex = Number;
}

But still, combobox always selecting the first item when I reopen the form.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • where do you re-initialize the combobox items after reopening? – lukai Feb 24 '23 at 11:09
  • You probably want to store the last selection in User Settings – Jimi Feb 24 '23 at 11:35
  • If **1** `Form1` is the _main_ form and you want to reopen the app and have the combo box where you left it (User Settings) you may find this answer helpful https://stackoverflow.com/a/61978765/5438626. But if **2** `Form1` is a popup dialog that may be opened and closed multiple times from a 'parent' form then this answer might be closer to what you want https://stackoverflow.com/a/75009730/5438626. – IVSoftware Feb 24 '23 at 12:31
  • What is `Number`? Where and when do you set it? I suspect you can hardly set it before you call the constructor. – Thomas Weller Feb 24 '23 at 12:44

1 Answers1

0

You can store this in the user settings provided by Visual Studio. Right-click on your project in visual studio and select Properties -> Settings. Add an item in the table such as defaultNumber set its type to int and scope user.

Make sure to add "using YourProjectName.Properties" at the top.

Then inside your form closing event write a code to save this setting.

Settings.Default.defaultNumber = combobox1.SelectedIndex;
Settings.Default.Save();

and in your form load event you should write

combobox1.SelectedIndex = Settings.Default.defaultNumber;