0

我觉得这应该很容易,但我似乎无法弄清楚。我有一个设置文件 Settings1.settings,其中包含 20 个文本框的条目(n1 到 n10 和 c1 到 c10)。

目前,我将文本框文本保存到 Form1_FormClosing 上的设置文件中,如下所示:

Settings1.Default.n1 = n1.Text;
Settings1.Default.n2 = n2.Text;
...
Settings1.Default.n10 = n10.Text;

Settings1.Default.c1 = c1.Text;
Settings1.Default.c2 = c2.Text;
...
Settings1.Default.c10 = c10.Text;

我将如何用循环做类似的事情?我的想法是这样,但显然它不起作用:

int count = 1
while (count < 11)
{
    Control n = panel2.Controls.Find("n" + count.ToString(), true).Single();
    Settings1.Default.n = n.Text; //Settings1.Default.n is an invalid statement ...

    Control c = panel2.Controls.Find("c" + count.ToString(), true).Single();
    Settings1.Default.c = c.Text; //Settings1.Default.c is an invalid statement ...

    count++;
}

解决“Settings1.Default.n + count”的正确方法是什么?

谢谢!!

4

3 回答 3

1

我建议将设置“n”和“c”的类型更改为“System.Collections.Specialized.StringCollection”,并像常规列表或数组对象一样处理它,例如:

Settings1.Default.n.Clear()
Settings1.Default.c.Clear()
int count = 1
while (count < 11)
{
    Control n = panel2.Controls.Find("n" + count.ToString(), true).Single();
    Settings1.Default.n.Add(n.Text);

    Control c = panel2.Controls.Find("c" + count.ToString(), true).Single();
    Settings1.Default.c.Add(c.Text);

    count++;
}

或者,我认为您也可以通过字符串访问设置条目,如下所示:

Settings1.Default["n" + count.ToString()] = n.Text;
于 2012-11-13T16:36:44.930 回答
0

bde's suggestion is undoubtedly the better way to do it, however, you could use the GetProperty method of Type. This can be used to get a collection of properties. You can then loop through them and use PropertyInfo.SetValue to set them.

于 2012-11-13T16:44:33.930 回答
0

您可以使用 ConfigurationManager 来读取 AppSettings。这是一个 NameValueCollection,您可以查询特定键(例如,名称以“n”或“c”开头的键)。您还可以将控件分组到控件数组中,以便 n[1] 包含对 n1 的引用、n[2] 对 n2 的引用,依此类推。

于 2012-11-13T16:47:04.847 回答