将项目添加到 my.settings StringCollection [英] Adding Items to my.settings StringCollection

查看:33
本文介绍了将项目添加到 my.settings StringCollection的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.Usernames.Add(textbox1.Text)

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

But I am thrown this error when the code executes:

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

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

有什么想法吗?感谢您的回答,谢谢.

Any ideas? I appreciate any answer, thanks.

推荐答案

很可能你还没有实例化它.

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."

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

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.

这篇关于将项目添加到 my.settings StringCollection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆