1

I'm refactoring my code to implement multi-database work. I use System.Data.Common classes and factory to create Exact objects for currently selected database engine. Some connection definitions in Designed looks like:

private System.Data.Common.DbConnection cn;

and assigment is:

private void InitializeComponent()
{
...
    this.cn = SqlFactory.CreateConnection();
...
}

and SqlFactory code looks like:

public DbConnection getConnection()
{
    return (TSqlConection)Activator.CreateInstance(typeof(TSqlConection));
}

It works okay at runtime, but when i'm trying to open any form in VS Designer i've got errors like the following:

The variable 'cn' is either undeclared or was never assigned.

And Designer can't display form for editing.

How can i fix it?

Tyree Jackson
  • 2,588
  • 16
  • 22
qmor
  • 568
  • 6
  • 20
  • 2
    http://stackoverflow.com/questions/8521600/the-variable-variable-name-is-either-undeclared-or-was-never-assigned – Kapol Oct 30 '15 at 09:43

2 Answers2

2

The InitializeComponent method should not be touched manually in general, the Form Designer always overwrites its contents once you open it. Visual Studio usually adds an autogenerated comment about that in *.Designer.cs. Also, I would suggest not to try to create any DB connection in the default constructor (the one without parameters), because Visual Studio calls it when you attempt to open your form in the Designer.

So, your options are

  1. Create an additional constructor for your form with parameters, this one can try to initialize your DB connection.
  2. Use the Load event of the form.
  3. Create an additional method called, for instance, InitConnections in the form, this method will perform a necessary initialization. You call it right after your form is created somewhere in your code.
1

Remove this.cn = SqlFactory.CreateConnection(); and everything about cn from Designer.cs. Add this part after InitializeComponent();.

Now you can edit form and no errors will occurre.

mrhotroad
  • 306
  • 3
  • 10