posted 8/25/2010 by Raghav Khunger
In this blog I will show how to add custom controls to Visual Studio toolbox. I always prefer to drag and drop or double click the controls icons from toolbox so that I can use those controls on my page. Now this is fine as per controls which come with Visual Studio, so what to do with the controls made by user own ? how to add them in the toolbox ?. Let's start with making a custom control first. We will make a custom textbox control which will derive from ASP.NET textbox control but will have a new property named "MyTextBox". Below the code for it :
using System.Drawing; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TestProject { public class MyTextBox : TextBox { [AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), ToolboxBitmap(typeof(TextBox)), ToolboxData("<{0}:MyTextBox1 runat=\"server\" />")] public string MyNewProperty { get { return (string)ViewState["MyNewProperty"]; } set { ViewState["MyNewProperty"] = value; } } } }
Let's register it in web config:
<pages> <controls> <add tagPrefix="MyControl" namespace="TestProject" assembly="TestProject"/> </controls> </pages>
Okay now build the the library which contains the custom control. Let's say the name of the dll is "TestProject.dll"
Below are the steps with the screen shots to accomplish our goal
Right Click over the toolbox and select "Add Tab" option from the menu.
Give a proper name to the tab say "Custom Controls"
Right click on the "Custom Controls" tab which we just created and then select "Choose Items" option from the menu.
Click "Browse" button
Select the dll which contains our custom control say "TestProject.dll"
Click "Ok" button.
You will see a new item will be added to your "Custom Control" tab.
Next drag and drop the item over the form or double click the item so as to place it over the form and below is the screen shot which I got after clicking that "MyTextBox" item.
Above you must have noticed that our new item which was added in the toolbox contains the ASP.NET "textbox" icon from where did it comes ? It is because of the "ToolboxBitmap(typeof(TextBox))" we added in our custom control code. To read more about "ToolboxBitmap" you can refer http://msdn.microsoft.com/en-us/library/4wk1wc0a(VS.71).aspx
That's it we are done with adding custom control to Visual Studio toolbox.
Do let me know your feedback, comments.
Very detailed and in-deep explained example! Great work Raghav!
What kind of email newsletter would you prefer to receive from CodeAsp.Net?18