Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving last saved value in C# WinForms

Tags:

c#

Suppose I have one form where a combo box has some options. Now, at the first run of this program, user selects a option from combo box and saved it through a button click or something. Now, If user terminates the application and run again for the 2nd time, is there any way to retrieve the last saved selection?

That means, if you select option1 from the combo box and terminate the application. after some time, you again start the application, now your combo box should show option1 as selected because at the previous session, you selected it.

I hope you'll understand what i think.


1 Answers

Use Settings

// To Load (after combo box binding / population)
private void LoadSelection()
{
    int selectedIndex = 0;

    if (int.TryParse(Properties.Settings.Default.comboBoxSelection, out selectedIndex))
    {
        cbMyComboBox.SelectedIndex = selectedIndex;
    }
}

// saving on button click.
private void saveButton_Click(object sender, EventArgs e)  
{  
    //set the new value of comboBoxSelection 
    Properties.Settings.Default.comboBoxSelection = cbMyComboBox.SelectedIndex;  

    //apply the changes to the settings file  
    Properties.Settings.Default.Save();  
}  

See here for more detail.

like image 155
Lloyd Powell Avatar answered Aug 19 '26 17:08

Lloyd Powell