Defining your classes in the code behind

I noted a very interesting thing today. If you are trying to make classes inside your code behind than your class which is at top of the page should always be the one which inherits from the System.Web.UI.Page or else your will not get errors while creating controls on design time. This code will give error message when you drag and drop any server control on the form.

public class MyClass 
	{ 
		
		public string name; 
				
		public void Foo(string cat) 
		{
			
 
		}

		private void InitializeComponent()
		{
		
		}
	
//		public  void InitializeComponent() 
//		{
//
//		}

		public void SecureMethod()
		{
 
		}

	}
	
	public class WebForm1 : System.Web.UI.Page
	{
		protected System.Data.SqlClient.SqlConnection myConnection;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			Assembly myAssembly = Assembly.LoadFrom(Server.MapPath(@"bin\AzamTest.dll")); 
			Type myType = myAssembly.GetType("AzamTest.MyClass"); 
 
			MethodInfo getsalary= myType.GetMethod("Foo"); 
			object obj=Activator.CreateInstance(myType); 
			object[] p=new object[1]; 
			p[0]="Hello bipin"; 
			getsalary.Invoke(obj,p); 			
				
		}

And this will work fine.
public class MyClass : System.Web.UI.Page
	{
		
		// same code from the class defined above 

 	} 

Also if you define the MyClass after the WebForm1 which inherits from System.Web.UI.Page than it will work fine too. Plus if you custom class is the first class in the code behind. Than go to the design view and come back again on the code behind and the InitializeComponent method and all the controls are authomatically added to your custom class. Finally, I don't think Visual Studio.NET likes me doing all this because if clears out Page_Load method and InitializeComponent method of my Custom Class.

Print | posted @ Wednesday, July 20, 2005 11:35 AM

Twitter