The variable 'variable_name' is either undeclared or was never assigned
Asked Answered
P

16

48

I have a question related to the error on the title. Im working with c# and Visual Studio 2010.

I have a form declared as "public class FormularioGeneral : Form", which is the base for the rest of the forms in my application. When i try to access the Designer View i get this error several times, as you can see in the image:

Sample of errors All the errors references lines inside the InitializeComponent method, where the value is assigned to a property like this one:

[...]            
this.PanelMargenIzquierdoCapaBase.BackColor = m_ColorCapaBase;
[...]

But all the variables are declared in the same class as read-only properties and all of them are assigned inside a method which is called in the constructor.

Declaration of properties:

    protected Color m_VariableName;
    public Color VariableName
    {
        get { return m_VariableName; }
        set { }
    }

Constructor code:

    public FormularioGeneral()
    {
        ConfigurarUI();
        AccionesConstructor();
        InitializeComponent();
        PostInicializacionComponentes();
        EstablecerIcono();
        InicializarLocalizacionFormulario();
    }

ConfigurarUI method:

public virtual void ConfigurarUI()
{
        [...]

        m_AltoBordeSuperiorCapaBase = 30;
        m_AltoBordeInferiorCapaBase = 7;
        m_AnchoBordesLateralesCapaBase = 7;

        m_ColorCapaBase = Color.FromArgb(50, 100, 150);
        m_ColorTextoCapaBase = Color.White;
        m_ColorTextoBotonAplicacion = Color.Black;

        m_FuenteTextoIzquierdoCapaBase = new System.Drawing.Font("Verdana", 11.0F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        m_FuenteTextoCentroCapaBase = new System.Drawing.Font("Verdana", 14.0F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
        [...]
}

So, as far as i know, all the variable which are giving the errors are correctly declared and have a value assigned before the InitilizeComponent function is called.

Im stuck at this point and dont know what to do to solve the problem. Hope some of you can help me with this issue.

Ppi answered 15/12, 2011 at 14:26 Comment(5)
be sure you call your constructor before using your code. public Form1() { FormularioGeneral(); }Erastian
Hello Bruno. The error is produced inside the InitializeComponent method, when i assign the m_* value to some property (for example, when i set the text color of a button --> this.Button1.ForeColor = m_TextButtonColor)Ppi
also discussed here: #1915683Surpass
And here also: #12343260Impregnable
I can't write an answer due to not being sure what's going on, and am trying to solve an probably different maybe unrelated problem, but experimenting with my main Solution and an small hackjob custom control project, I find that I must chose "Any CPU" not x86 or x64 to avoid getting these 'variable undeclared' errors.Wellrounded
N
50

So, I have had the same problem in the past, for fix I did the following:

  • Solution → Clean Solution;
  • Build → Rebuild Solution;
  • Close Visual Studio, re-open.

Thanks a lot to Marshall Belew!

Noella answered 2/7, 2013 at 20:56 Comment(2)
I ways do that, and it works, but I wonder why this error is happening and how can I avoid that. Or this is simple a VS bug?Impregnable
In case someone finds their way here, the problem might arise from the constructor of the offending control being declared anything other than public.Ecuador
C
23

In my case, I had an older Windows Forms project where InitializeComponents() started like this:

private void InitializeComponent()
{
    var componentResourceManager = new ComponentResourceManager(typeof(MyForm));
    ...

This resulted in an error message later on when accessing the componentResourceManager inside InitializeComponent():

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

When comparing with a newly created form, I saw that it was similar to my non-working form, except for one thing:

The variable was not named componentResourceManager but simply resources.

Solution

After doing a rename on my variable to also have the name resources, everything works successfully:

private void InitializeComponent()
{
    var resources = new ComponentResourceManager(typeof(MyForm));
    ...

The Windows Forms Designer in Visual Studio 2017 did open the form correctly.

Contiguous answered 16/7, 2018 at 9:4 Comment(3)
Thanks, worked for me. Can you give any explanation why it worked this way?Monsour
Amazing! This also worked for me. Can someone please explain why changing to resources works?Patagium
Damn, where did you get that knowledge? Worked like a charm.Burgas
M
14

I ran into this error because my project is x64 only. Apparently Visual Studio, being a 32bit application, cannot load any forms or controls compiled to 64bit in the designer. It makes total sense, but the error gives you no indication that is the problem.

See the answer to Visual studio designer in x64 doesn't work.

The workaround is to change your project to Any CPU when designing, then back when building.

Marsipobranch answered 6/7, 2016 at 15:41 Comment(1)
Too bad even in visual studio 2017 they still don't tell the real reason... 2 hours on the web, after trying manually change the GUI... all that until I came to here...Passible
I
8

Maybe the error occurs due to your constructor code. Place InitializeComponent(); at the beginning of the constructor like this:

public FormularioGeneral()     
{         
    InitializeComponent();
    ConfigurarUI();         
    AccionesConstructor();
    PostInicializacionComponentes();         
    EstablecerIcono();         
    InicializarLocalizacionFormulario();     
} 

Explanation:

The variables are initialized in that method.

Ishtar answered 15/12, 2011 at 14:29 Comment(6)
I already tried it, but this doesnt solve the problem. Anyway, the variables are declared without value. A value is assigned inside the "ConfigurarUI" method (So this method should be executed before using the variable). Finally, in the InitializeComponent the variables are used.Ppi
As far as I understand you correctly, have you changed the code in the InitializeComponent to use your variables?Ishtar
I dont think the assignments were "hardcoded" in the InitializeComponent since it is auto-generated each time you compile. I assume that the values were assigned through the Designer, but cant assure it since other guy started this project and im the "sucessor" :PPpi
Poor "sucessor". The designer doesn't generate member variables with an "m_" at the beginning. So this was "handmade" and it will make trouble. There is a comment to the "InitializeComponents" method, stating that one should never edit this. Try to solve problem in a different way, maybe by setting the values after InitializeComponents.Ishtar
I know the m_* variables are created manually, but i think you are right. The errors point the assingments made inside the InitializeComponent like "this.Button1.ForeColor = m_TextButtonColor", which should be made through the designer and seems like it was hardcoded. Im going to try to change those hardcoded assingments to this one: "this.Button1.ForeColor = Color.Black" which is the value stored in the m_TextButtonColor :PPpi
As a clarification, the designer doesn't execute your code, it reads your code, and specifically, it only reads the InitializeComponent() method. Any initialization code you have outside of that is beyond its understanding.Titled
I
3

I had the same problem and cleaning and rebuilding did not work for me.

In my case the problem was caused by the Visual Studio designer loading referenced DLLs from the GAC instead of loading them from the <HintPath> directory specified in the .csproj file. The DLLs in the GAC did not have the same version as the locally stored DLLs.

When I updated the DLLs in the GAC to have the same version everything worked OK again.

Idleman answered 4/3, 2015 at 9:18 Comment(0)
F
3

Don't put anything other than InitializeComponent(); in the constructor. You can put the code from there in events like Load().

Fructify answered 5/8, 2018 at 1:3 Comment(0)
S
2

I had this issue when my user control had some code in the constructor which was related to runtime resource. I added null check and it fixed.

        InitializeComponent();
        if (MyConfig!= null)
        {
            this.label2.Text = MyConfig.text1;
            this.label3.Text = MyConfig.text2;
            this.label1.Text = MyConfig.text3;
        }
Sarasvati answered 27/4, 2017 at 10:35 Comment(0)
K
2

In my case, I added a third party control in my Toolbar(via a .dll file), and draw one of it in my form. And for some reason, my Toolbar clean this third party control out of the general group(I added it in the general group), so VS cannot find this control. Here is what I done to slove this problem:

  1. Add this control into the Toolbar.
  2. Clean the solution
  3. Rebuild the solution

Redraw the control if neccessary.

Kurys answered 15/8, 2017 at 16:22 Comment(0)
T
2

User Controls were caused problem and after trying all suggestions, (Focus solution then Alt+Enter) changing solution's Platform Target from x64 to Any CPU solved the problem.

Troytroyer answered 1/11, 2018 at 9:26 Comment(0)
L
1

About the variables, can you simply initialize them in the declaration? I think that would suffice, even if you change the value later. From what I'm seeing, the compiler is unable to check whether you have initialized them or not because it's not directly on the constructor code, it's being done on a virtual method which will evaluate only at runtime.

So, instead of:

protected Color m_VariableName;
public Color VariableName
{
    get { return m_VariableName; }
    set { }
}

Do:

protected Color m_VariableName = Color.White; // Or null
public Color VariableName
{
    get { return m_VariableName; }
    set { }
}

And a comment: you should avoid virtual calls in the constructor, which can lead to obscure errors in your application. Check it here.

Lewse answered 15/12, 2011 at 14:33 Comment(1)
Thanks for the answer. I tried to do as you say, initializing the variables in the declaration, but doesnt solve the problem :P I also read about the virtual methods, and copied all the code in the virtual method inside the constructor, to not need to make the call, but even so, the problem persist :PPpi
H
1

This error occurs for me while creating a third party control in InitializeComponent() which is called from form constructor. When I created it after InitializeComponent() it works fine for me.

public MyForm() //Form constructor
{         
    InitializeComponent();

    //Create/initialize third party control here with new operator    
}
Halloran answered 20/2, 2016 at 6:10 Comment(1)
This is exactly my problem, I have created some UserControl, and for some reason, the process to generate Design of the Form always complains. After I moved anything seems suspicious out of InitializeComponent, it works fine. ThanksPreachy
W
1

I am working with WPF inside of Windows Forms.

I hosted my WPF User Control in a Windows Forms Element Host. Due to that when InitializeComponent() got called I executed Code before reaching the InitializeComponent() of my WPF control. Tricky.

So I moved it out of my constructor, Clean Build, Rebuild, Restart VS and everything works as expected. Finally.

Withdrawal answered 28/7, 2016 at 10:42 Comment(0)
S
1

I have had the same problem and I fixed it. Actually Visual Studio only works with X86 controls and you can't create a user control in X64 mode and use it.

You should add a new class library in Any CPU mode and build the class library. then you can add its DLL in your project. Done.

If it doesn't you must go to the Configuration manager and set the Active solution platform to X64 also do that for all subprojects. Remember that build option has to be checked. and go to the properties of the class library and click on the build tab. then set the platform target to Any CPU.

Schock answered 18/9, 2019 at 7:31 Comment(0)
P
0

First I had code that referenced something a type that the designer couldn't load (for whatever reason). Then I had code in the constructor that couldn't be executed from my local laptop. I decided the best option was to move the logic to the Load event and check if the component was in DesignMode and exit if it was.

Even this wasn't enough for me as the designer still tried to JIT the type that was later down in the method, so I had to move it out to a separate method to stop that from happening. Here's basically what I ended up with:

    private void userControl_Load(object sender, EventArgs e)
    {
        if (DesignMode) return;

        Initialize();
    }

    private void Initialize()
    {
        // do your work
    }

Special thanks to this SO answer which pointed me to a comment in a blog post about not accessing the DesignMode property until you're in the Load event...

Pilchard answered 1/3, 2019 at 20:25 Comment(0)
P
0

Renaming the variable componentResourceManager to resources solved error.

Unfortunately i had to change a ton of other items to get the designer working for Telerik reports designer

Protest answered 27/6, 2019 at 16:58 Comment(0)
D
0

In my Solution i had wrong Reference paths which i fixed in the .csproj files. After fixing that i could finally load the Form again.

Delanty answered 29/7, 2019 at 12:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.