开发者

C# ADO.NET Exception: ExecuteReader: Connection property has not been initialized

开发者 https://www.devze.com 2023-03-23 10:56 出处:网络
Hi I am trying to get some data from a simple database that I have created using a separate control on the main form. This program runs however when I try to view the main form in designer view I get

Hi I am trying to get some data from a simple database that I have created using a separate control on the main form. This program runs however when I try to view the main form in designer view I get this exception "ExecuteReader: Connection property has not been initialized."

This is my code for the 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));

            }
        }
    }
}

And my main form:

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;
        }
    }
}

This all seems to work fine if I call getData() and addData() in a button handler but not in form load. The project still runs without errors I just get that exception when trying to view designer view in the main form.


This happens because Visual Studio creates an instance of your form in the Designer, so any _Load type events and your default constructor will be executed.

You can check if you are in Design time by examining the DesignMode property, although there are limitations but your case DesignMode should suffice.

Example:

void MyMainForm()
{
  InitializeComponent();

  //Do any UI Init Stuff (Icons etc.) here.

  if (!DesignMode)
  {
    //Business Logic (call databases etc.) here.
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消