您好,我正在尝试从一个简单的数据库中获取一些数据,该数据库是我在主窗体上使用单独的控件创建的。该程序运行但是当我尝试在设计器 View 中查看主窗体时我收到此异常“ExecuteReader:连接属性尚未初始化。”
这是我的 GetControl 代码:
namespace Controls
{
public partial class GetControl : UserControl
{
private SqlCeConnection mConnection = null;
private SqlCeDataReader dataReader = null;
public SqlCeConnection Connection
{
set { mConnection = value; }
}
public GetControl()
{
InitializeComponent();
}
private void GetControl_Load(object sender, EventArgs e)
{
getData();
addData();
}
private void getData()
{
SqlCeCommand command = new SqlCeCommand("SELECT FirstName, LastName FROM Contacts", mConnection);
dataReader = command.ExecuteReader();
}
private void addData()
{
while (dataReader.Read())
{
contactList.Items.Add(dataReader.GetString(0) + " "
+ dataReader.GetString(1));
}
}
}
}
还有我的主要形式:
namespace Phonebook_Application
{
public partial class Phonebook_MainForm : Form
{
SqlCeConnection con = new SqlCeConnection("Data Source=Phonebook.sdf;Persist Security Info=false;");
public Phonebook_MainForm()
{
InitializeComponent();
con.Open();
getControl1.Connection = con;
}
}
}
如果我在按钮处理程序中调用 getData() 和 addData() 而不是在表单加载中调用,这一切似乎都能正常工作。该项目仍然运行没有错误我只是在尝试以主窗体查看设计器 View 时遇到该异常。
最佳答案
发生这种情况是因为 Visual Studio 在设计器中创建了您的表单实例,因此将执行任何 _Load 类型事件和您的默认构造函数。
您可以通过检查 DesignMode 来检查您是否处于设计时间属性(property),虽然有limitations但您的案例 DesignMode 应该足够了。
例子:
void MyMainForm()
{
InitializeComponent();
//Do any UI Init Stuff (Icons etc.) here.
if (!DesignMode)
{
//Business Logic (call databases etc.) here.
}
}
关于C# ADO.NET 异常 : ExecuteReader: Connection property has not been initialized,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6844069/