Dynamically compiling winform code gives error in c #

I have a simple windows application where a Win Form is dynamically created and displayed along with a toolbar. The user drags and drops a control on this dynamically generated form and writes code accordingly. Below is not all the code, but the part where I have to face the problem. I am trying to compile user-written code at runtime, but it gives me the error " In the form 0 -> The name" InitializeComponent "does not exist in the current context Line error (12): CS0103"

            // small piece of code
            string SecondLine = @"public partial class Form1 : Form
                                      public Form1()

            Form1 frm =new Form1();

        frm.textBox1.Text = "using System;" + Environment.NewLine
        + "using System.IO;" + Environment.NewLine + "using System.Drawing;" +                    Environment.NewLine + "using System.Windows.Forms;" + Environment.NewLine + Environment.NewLine + "namespace MiniCompiler{" + Environment.NewLine + Environment.NewLine;

            frm.textBox1.Text = frm.textBox1.Text + SecondLine.ToString();
            frm.textBox1.Text = frm.textBox1.Text + Environment.NewLine + Environment.NewLine + "static class Program{" + Environment.NewLine + " [STAThread] " + Environment.NewLine + "static void Main()" + "{" + Environment.NewLine;

            string firstLine = "Application.EnableVisualStyles(); " + Environment.NewLine + "Application.SetCompatibleTextRenderingDefault(false);" + Environment.NewLine + "Application.Run(new Form1());";

            frm.textBox1.Text = frm.textBox1.Text + Environment.NewLine + firstLine;   
            frm.textBox1.Text = frm.textBox1.Text.ToString() + Environment.NewLine + "}" ;


// to compile the code

 CSharpCodeProvider provider = new CSharpCodeProvider();
 ICodeCompiler compiler = provider.CreateCompiler();
 CompilerResults result = compiler.CompileAssemblyFromSource(param,code); 


I'm really not sure what the error might be when compiling Winform here.



source to share

1 answer

I think the error message is correct. I can't see where your InitializeComponent () is defined - the method that gets called in the constructor of the Form1 class.

Since the form is generated as a partial class, there can be (and actually is by default) more than one file, the witch contains members of that class. By default, you have two files. In your case Form1.cs and Form1.Designer.cs. Both together describe the Form1 class.

The InitializeComponent method is not inherited. It is defined in the same class as in another file.

    private void InitializeComponent()
        this.components = new System.ComponentModel.Container();
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.Text = "Form1";


You can copy this method from another partial part of Form1-Class to your SecondLine-String. Then it should work, I guess.

Look in this file



All Articles