Sometimes when you work on your code, you may not notice that some actions may damage another area of your project. This exception is usual on lazy developers that declare multiple classes inside a single file. The problem is when you add multiple classes of a file that contains a class that extends the Form class of .net (it will be rendered on the designer), so when the first class of the file is not the one that extends the Form class, the renderer will fail.
In this article, we'll explain you easily how to fix this exception in your renderer.
1. Check if the class with the issue really contains 2 classes
The error is basically triggered as mentioned, because of the existence of 2 classes in a single file, for example, the following file Form1.cs
contains 2 classes inside the same namespace:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Sandbox
{
// Class #1
public class Wow64Interop
{
[DllImport("Kernel32.Dll", EntryPoint = "Wow64DisableWow64FsRedirection")]
public static extern bool DisableWow64FSRedirection(bool disable);
}
// Class #2
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
}
}
The Form renderer of Windows will always take the first class inside the file to render the form. As in our case, the first class that you can find is theĀ Wow64Interop
class, the renderer will throw the exception as it's unable to render a class that doesn't extends the Form
class of .NET.
2. If there's another class, set the Form class as first
To solve the issue, just change the order of the class in your file, for example:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace Sandbox
{
// Class #2
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Hello");
}
}
// Class #1
public class Wow64Interop
{
[DllImport("Kernel32.Dll", EntryPoint = "Wow64DisableWow64FsRedirection")]
public static extern bool DisableWow64FSRedirection(bool disable);
}
}
Note as well that not only for convenience but maintainability, every class should be inside a single file. The same logic applies for other languages like Visual Basic.
Happy coding !