保存表单并在重新打开时显示

本文关键字:新打开 显示 表单 保存 | 更新日期: 2023-09-27 18:03:54

我已经编写了一个程序,当我打开一个文件时,该程序将文件的第一行并将其放置到DataGridView的第一列。对于第二个列的每一行,用户有一个组合框的3个值可供选择。

发布并打开可执行程序后,我必须从openFileDialog中打开一个文件并选择组合框。但是,当我关闭并重新打开时,既没有打开文件,也没有选择组合框。我需要他们。

我需要保存所做的操作,以便下次打开程序时选择组合框的值。

你有什么建议?

private void button1_Click(object sender, EventArgs e)
        {
            //  opens **BROWSE**
            openFileDialog1.Title = "select CSV for check ";
            string filename = "";
            DialogResult result = openFileDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                filename = openFileDialog1.FileName;
                textBox1.Text = filename;



                string line;
                // Read the file and display it line by line.
                //read the path from textbox
                System.IO.StreamReader file = new System.IO.StreamReader(textBox1.Text);
                stringforData = file.ReadLine();      
                while ((line = file.ReadLine()) != null)
                {
                    // puts values in array 
                    fileList.Add(line.Split(';'));
                }
                file.Close();

                this.ToDataGrid();
            }

     }

private void button2_Click(object sender, EventArgs e)
        {
            this.textBox2.Clear();
    //*************  PUTS COLUMN 2 TO A STRING[]  ************************
            string[] colB = new string[dataGridView1.Rows.Count];
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                colB[i] = Convert.ToString(dataGridView1.Rows[i].Cells[1].Value);
          }
 //*************************************************************************

 public void ToDataGrid()
        {
            string[] split = stringforData.Split(';');

            foreach (string item in split)
            {
                dataGridView1.Rows.Add(item);
            }
        }

保存表单并在重新打开时显示

您可以直接不关闭程序,而是禁用它。这样你就不需要保存任何东西,它们都还在那里,只是没有显示。

设置YourForm.Enabled = false;为隐藏,true为显示

您必须将您的设置保存在程序关闭时不会丢失的地方。一种简单的方法是将它们写入文件。对于非常的简单示例,可以使用以下代码保存变量:

        List<string> variables = new List<string>();
        variables.Add(variable1);
        variables.Add(variable2);
        File.WriteAllLines("settings.txt", variables);

在程序启动时再次加载它们的代码。在尝试读取文件之前,一定要检查该文件是否在那里,因为第一次运行时它不会在那里。

        List<string> variables = File.ReadAllLines("settings.txt");
        string variable1 = variables[0];
        string variable2 = variables[1];

我不会在发布的应用程序中单独使用此代码,它只是基础的一个例子。有很多潜在的问题。如果用户没有管理员权限,如果应用程序在某些文件夹(如Program Files)中运行,则会出现异常。如果当前目录在程序运行期间发生了变化,那么保存到上述相对路径可能不会每次都保存在相同的位置,您需要确定要保存到的绝对路径。像这样的IO操作需要有良好的错误检查和处理。

也有保存变量到注册表的方法,虽然我不喜欢这样做。保存设置是几乎每个桌面应用程序都需要做的事情。我相信。net不包括读写ini文件的标准函数。您可以将Win32函数与DLLImport一起使用,但这很难看。我自己写了一个,用在我所有的应用程序中。