我想存储一次从应用程序内部保存的服务器名称的用户输入。我在SettingsForm类中超出范围的索引设置中出现错误(如下所示的错误行)。我相信我的ServerName属性只有大小1,那么我将如何更改它呢?还是在我的代码中需要更改其他内容?
我不确定是否将多个字符串存储到一个属性。我一直在尝试不同的方法,但是对于C#和WinForms应用程序我是新手。这是我一直在尝试的代码:
UserSettings类:
[UserScopedSetting()]
[DefaultSettingValue("Enter Server Name")]
public String[] ServerName
{
get
{
return (String[])this["ServerName"];
}
set
{
this["ServerName"] = (String[])value;
}
}
SettingsForm类:
private void saveSettingsButton_Click(object sender, EventArgs e)
{
//loop through all servers
for (int i=0; i<serverCounter.Value; i++)
{
TextBox currentTextBox = (TextBox)servers[i, 0];
us.ServerName[i] = currentTextBox.Text; //ERROR
currentTextBox.DataBindings.Add("Text", us, "ServerName");
}
us.Save();
this.Close();
}
潜在问题:具有什么价值serverCounter.Value
?us.ServerName []如何实例化?ServerName返回一个字符串数组,但在我看来,每个serverName应该是一个字符串,然后放入一个数组(或列表)中。
根据您显示的代码片段,我的猜测是serverCounter的特定值> 1,而us.ServerName始终是一个包含1个项目的数组(或者从不实例化)。这会给您索引超出范围的错误。
尝试使用public string ServerName
代替,public String[] ServerName
然后每次获得返回值时,都将该值放入数组中;或者,如果您不知道将输入多少服务器,则使用List会更好。
List<string> serverNames = new List<string>();
// Get currentName from user--I don't understand how your code is supposed to work
serverNames.Add(currentName); // this is the name entered by the user
然后使用foreach循环:
foreach (string name in serverNames)
{
//do something
}
如果事先知道有多少服务器,则可以使用字符串数组:
string[] serverNames = new string[serverCounter];
并且仍然使用foreach循环对其进行迭代。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句