将comboBox文本加载并保存到.txt

时间:2017-09-19 21:16:55

标签: c# .net winforms combobox

我正在编写一个脚本,我可以在Windows窗体中的所有组合框中加载/保存文本。这是我用来将comboBox.Text保存到.txt文件的工作方法:

private void btnSave_Click(object sender, EventArgs e)
{
    try
    {
        System.IO.StreamWriter objWriter;
        // clear previous input curve values
        File.WriteAllText(@"C:\Users\Public\inCurves.txt", String.Empty);
        objWriter = new System.IO.StreamWriter(@"C:\Users\Public\inCurves.txt", true); // true wil make program add new lines 
        // some combobox voodoo
        var combBoxes = this.Controls.OfType<ComboBox>().Where(x => x.Name.StartsWith("comboBox"));
        foreach (var cmbBox in combBoxes)
        {
            objWriter.Write(cmbBox.Text);
            objWriter.Write("*");
        }
        objWriter.Close();
        MessageBox.Show("Curve Names Successfully saved in C: Users Public inCurves.txt", "You Saved Your Curve Names ", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    catch (Exception ex)
    {
        MessageBox.Show("Error Saving Curve names \n" + ex.Message + "\n" + ex.StackTrace);
    }
}

这是我用来从.txt加载已保存的comboBox信息的方法。

private void btnLoad_Click(object sender, EventArgs e)
{
    try
    {
        string CurveNamesInText = "";
        char[] delimiter = { '*' };
        CurveNamesInText = System.IO.File.ReadAllText(@"C:\Users\Public\inCurves.txt");
        string[] crvIn = CurveNamesInText.Split(delimiter);
        string BottomDepth = crvIn[0];
        string TopDepth = crvIn[1];
        var combBoxes = this.Controls.OfType<ComboBox>().Where(x => x.Name.StartsWith("comboBox")).ToList();
        for (int i=0; i < combBoxes.Count; i++ )
        {
            combBoxes[i].Text= crvIn[i];
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error Loading Curve names \n" + ex.Message + "\n" + ex.StackTrace);
    }
}

这两种方法适用于带有8个组合框的Windows窗体,但似乎不适用于具有70个以上组合框的窗体。

为什么有任何建议? objWriter有限制吗? .txt有一行,但每个文本字段(来自comboBoxes)由*字符分隔。

0 个答案:

没有答案