ran*_*zer 6 c# configuration user-controls winforms
我有一个应用程序通过数据层获取数据到表单,使用这样的东西:
public DataTable get(String query, ArrayList parameters = null)
{
using (iDB2Connection cn = new iDB2Connection(ConfigurationManager.ConnectionStrings["iseries"].ToString()))
{
// get the data and return them
}
}
Run Code Online (Sandbox Code Playgroud)
我有获取数据的表单,这很好.
但是,我创建了一个UserControl,它通过这个方法获取数据,当我运行我的项目时工作正常,但是,包含UserControl的表单会引发设计器异常.
"为了防止在加载设计器之前可能丢失数据,必须解决以下错误:"
我发现错误位于从中检索连接字符串<appSettings>.
它会抛出nullpointerexception.
但仅限于设计模式.当我忽略它时,一切正常,但是,我想知道如何解决这个问题.
<appSettings>通过我的UserControl访问它时为什么我的null?
更新1
似乎我的UserControl根本无法识别<appSettings>.
当我将此代码放入UserControl Load事件时,我也得到了一个null引用.
private void SelectUser_Load(object sender, EventArgs e)
{
txtLocation.Text = ConfigurationManager.AppSettings["location"].ToString();
}
Run Code Online (Sandbox Code Playgroud)
我找到了解决方案,在设计模式下,用户控件已经执行了加载事件中的代码。由于 App.config 在设计模式下不可用,因此未找到它,因此未加载它。所以我做了一些检查来检查是否处于设计模式:
bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);
if (designMode)
{
string location = ConfigurationManager.AppSettings["location"].ToString();
}
Run Code Online (Sandbox Code Playgroud)