【问题标题】:Retrieving last saved value in C# WinForms在 C# WinForms 中检索上次保存的值
【发布时间】:2012-01-26 14:00:29
【问题描述】:

假设我有一个表单,其中组合框有一些选项。现在,在该程序的第一次运行时,用户从组合框中选择一个选项并通过单击按钮或其他方式将其保存。现在,如果用户终止应用程序并再次运行 2 次,有没有办法检索上次保存的选择?

这意味着,如果您从组合框中选择 option1 并终止应用程序。一段时间后,您再次启动应用程序,现在您的组合框应显示 option1 已选中,因为在上一次会话中,您选择了它。

希望你能理解我的想法。

【问题讨论】:

标签: c#


【解决方案1】:

使用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();  
}  

here for more detail

【讨论】:

  • +1。请注意,您不需要TryParse:设置是强类型的,因此您可以简单地使用int 设置,而不必担心解析字符串。
【解决方案2】:

您必须手动保存该值并在程序启动时再次加载它。

使用 Visual Studio 的简单方法是创建一个 Settings 类。在VS中,右键单击您的项目,单击添加新,滚动到“设置文件”,添加。 VS 将向您显示一个 UI,您可以在其中创建您可以选择名称的设置对象中的新属性。

如果我创建一个名为“ComboboxValue”的字符串类型的新属性,我可以在代码中将其引用为Settings1.Default.ComboboxValue = "hello world";

这是上面的 MSDN:

http://msdn.microsoft.com/en-us/library/a65txexh(v=vs.100).aspx

【讨论】:

    【解决方案3】:

    您可以添加设置 在项目下的解决方案资源管理器中,属性文件夹 添加资源“字符串”给它一个名称“选定”例如 那么

    // this is save button
    Properties.Settings.Default.selected = comboBox1.SelectedIndex;
    Properties.Settings.Default.Save(); 
    
    // this is retrieve (use it in window_load event for example)
    comboBox1.SelectedIndex = Convert.ToInt32(Properties.Settings.Default.selected);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-15
      • 1970-01-01
      相关资源
      最近更新 更多