Geeks With Blogs
AzamSharp Some day I will know everything. I hope that day never comes.
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. Posted on Wednesday, July 20, 2005 11:35 AM | Back to top


Comments on this post: Defining your classes in the code behind

# re: Defining your classes in the code behind
Requesting Gravatar...
You shouldn't be defining an extra class in the same file as your code-behind class.

99% of the time these should go in a separate file anyway.
Left by Ben Scheirman on Jul 22, 2005 9:09 AM

# re: Defining your classes in the code behind
Requesting Gravatar...
I know ! I was just testing what will happen. Actually it will be a good test to define multiple Page classes and load each Page based on certain conditions. Kinda like LINUX multiple screens :)
Left by AzamSharp on Jul 22, 2005 10:07 AM

Your comment:
 (will show your gravatar)


Copyright © Mohammad Azam | Powered by: GeeksWithBlogs.net