vb.net 将项目添加到 my.settings StringCollection

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23452375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 17:30:35  来源:igfitidea点击:

Adding Items to my.settings StringCollection

vb.net

提问by user3105998

I have a string collection in my.settings. I want to add a string to it from a text box. I have tried this:

我在 my.settings 中有一个字符串集合。我想从文本框中向其中添加一个字符串。我试过这个:

 My.Settings.Usernames.Add(textbox1.Text)

But I am thrown this error when the code executes:

但是当代码执行时我抛出了这个错误:

System.NullReferenceException: Object reference not set to an instance of an object.

System.NullReferenceException:未将对象引用设置为对象的实例。

Any ideas? I appreciate any answer, thanks.

有任何想法吗?我感谢任何答案,谢谢。

回答by ???ěxě?

More than likely you have not instantiated it yet.

您很可能还没有实例化它。

If you run the program at this point, the setting isn't actually created so if you try to add or remove an item from the collection you'll get the error "Object reference not set to an instance of an object."

如果此时运行该程序,实际上并未创建设置,因此如果您尝试从集合中添加或删除项目,您将收到错误“未将对象引用设置为对象的实例”。

There are a couple of ways you can fix this. First, you can create the setting object at run time if it is null, but this is a bit of a hassle.

有几种方法可以解决这个问题。首先,如果设置对象为空,则可以在运行时创建设置对象,但这有点麻烦。

A better solution is to click the Value text box on the Settings page. Then click the ellipsis to the right to open a String Collection Editor. If you close this without adding any strings, the Settings window still doesn't actually create the setting object. To prevent that, add a string to the String Collection Editor and click OK. Then open the editor again, remove the string, and click OK. This keeps the setting object but it's empty.

更好的解决方案是单击“设置”页面上的“值”文本框。然后单击右侧的省略号以打开字符串集合编辑器。如果您在不添加任何字符串的情况下关闭它,“设置”窗口实际上仍然不会创建设置对象。为防止出现这种情况,请将字符串添加到字符串集合编辑器并单击确定。然后再次打开编辑器,删除字符串,然后单击“确定”。这保留了设置对象,但它是空的。

回答by user3697824

Another way to do this on the fly is in the Form Load event or Sub Main depending on how your app starts:

另一种动态执行此操作的方法是在 Form Load 事件或 Sub Main 中,具体取决于您的应用程序的启动方式:

' initialize the collection ias needed:      
If My.Settings.Usernames Is Nothing Then
   My.Settings.Usernames = New System.Collections.Specialized.StringCollection
End If

Forcing it to initialize by adding a fake string in Settingsis a nice to know and keeps it a Design-Time task. But this is pretty simple and treats it like any other object which needs to be instanced before use.

通过在其中添加一个假字符串来强制它进行初始化Settings是一个很好的了解,并将其保留为设计时任务。但这非常简单,并且像对待任何其他需要在使用前实例化的对象一样对待它。