ASP.NET FAQ - Custom Controls

How can I create a server control?

The below example is a demonstration of a simple server control which creates a Text Box.

Follow the below steps to create a new server control.

  1. Open VS.NET 2005.
  2. In File->New Select the Project submenu.
  3. In the Dialog window ,Select the Window, and select the WebControlLibrary.
  4. Select an appropriate path and give a name as TextControl, to create a new server control.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Text;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;

namespace WebCustomControl1
{
	[DefaultProperty('Text')]
	[ToolboxData('<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>')]
	public class WebCustomControl1 : WebControl
	{
		public TextBox _text = new TextBox();
		[Bindable(true)]
		[Category('Appearance')]
		[DefaultValue('')]
		[Localizable(true)]
		
		public string Text
		{
			get
			{
				String s = (String)ViewState['Text'];
				return ((s == null) ? String.Empty : s);
			}
			set
			{
				ViewState['Text'] = value;
			}
		}
	
		protected override void CreateChildControls()
		{
			 _text.Width = 200;
			 _text.Height = 50;
			 _text.Text = 'Server Control Creation';
			this.Controls.Add(_text);
		}

		protected override void RenderContents(HtmlTextWriter writer)
		{
			this.EnsureChildControls();
			this.RenderChildren(writer);            
		}
	}
}

Here is an article from ftp online: Build an ASP.NET Server Control that explains how to build a ‘Login Control’.

Permalink
How can MultiView Control be created in 2.0?

A MultiView is a non-visual control that provides a pallette where a several view Controls can be placed. A view control is another non-visual control where you can place the user interface controls.It is simillar to that of a Tab control.The below code demonstrate how MultiView can be created,

<div>
	<asp:Button id='Button1' runat='server' Text='View 1' OnClick='Button1_Click' />
	<asp:Button id='Button2' runat='server' Text='View 2' OnClick='Button2_Click' /> 
	<asp:Button id='Button3' runat='server' Text='View 3' OnClick='Button3_Click' />
	<br />
	<br />
	<asp:MultiView id='MultiView1' runat='server' ActiveViewIndex=0>
		<asp:View id='View1' runat='server'>
			Content Here (View 1)...
		 	<asp:BulletedList  ID='BulletedList1' runat='server'>
				<asp:ListItem>My Schedule On 1st Week</asp:ListItem>
				<asp:ListItem>My Schedule On 2nd Week</asp:ListItem>
				<asp:ListItem>My Schedule On 3rd Week</asp:ListItem>
				<asp:ListItem>My Schedule On 4th Week</asp:ListItem>
			</asp:BulletedList>
		</asp:View>
		<asp:View id='View2' runat='server'>
			Content Here (View 2)...
			<asp:Calendar ID='Calendar1' runat='server' BackColor='#FFFFCC' 
				BorderColor='#FFCC66' BorderWidth='1px' DayNameFormat='Shortest' 
				Font-Names='Verdana' Font-Size='8pt' ForeColor='#663399' Height='200px'
				 ShowGridLines='True' Width='220px'>
				<SelectedDayStyle BackColor='#CCCCFF' Font-Bold='True' />
				<TodayDayStyle BackColor='#FFCC66' ForeColor='White' />
				<SelectorStyle BackColor='#FFCC66' />
				<OtherMonthDayStyle ForeColor='#CC9966' />
				<NextPrevStyle Font-Size='9pt' ForeColor='#FFFFCC' />
				<DayHeaderStyle BackColor='#FFCC66' Font-Bold='True' Height='1px' />
				<TitleStyle BackColor='#990000' Font-Bold='True' Font-Size='9pt' 
				ForeColor='#FFFFCC' />
			</asp:Calendar>
		</asp:View>
		<asp:View id='View3' runat='server'>
			Content Here (View  3)...
			<br />
			<asp:Label ID='Label1' runat='server' Text='Schedule Details'></asp:Label>
		</asp:View>
	</asp:MultiView>
</div>
Permalink
What is an Validation Groups in 2.0 and how can u create them?

Validation Groups allows the different section of the webpage to be validated seperately. All the ASP.NET 2.0 Validation controls,interactive form controls like TextBox,list controls Button and other controls that are used to submit a webform have validationGroup property. The default value of this property is the empty string. When a button with a ValidationGroup property is clicked all of the validation controls on the page with the same ValidationGroup property value are executed.

On postback, the Page.IsValid property checks the validity of all of the validation controls. Programmatically it can be checked by the Validate() Method.

<html>
	<head runat='server'>
		<title>Validation Groups</title>
		<script runat='server'>
			void Group1Click(Object s, EventArgs e)
			{
				if (Page.IsValid)
				{
                         		                	lblResult.Text = 'Name Validated & Submitted';
				}
			}

			void Group2Click(Object s, EventArgs e)
			{
				if (Page.IsValid)
				{
					lblResult.Text = 'Age Validated & Submitted';
				}
			}
		</script>

	</head>
	<body>
		<form id='form1' runat='server'>
			<div>
				<asp:Label ID='lblResult' Runat='Server' />
    				<fieldset style='padding:20px'>
					<legend>Name</legend>
					<asp:Label ID='Name' runat='server' Text='Name:'></asp:Label>
	       				<asp:TextBox id='TextBox1' Runat='Server'/>
					<asp:Button ID='Button1' ValidationGroup='Group1' Text='Submit' 
						OnClick='Group1Click'  Runat='Server' />
					<asp:RequiredFieldValidator ID='RequiredFieldValidator1' 
						ValidationGroup='Group1'  ControlToValidate='TextBox1'
					       	Text='Field Cannot Be Empty' Runat='Server' />
				</fieldset>
        
    				<fieldset style='padding:20px'>
					<legend>Age</legend>
					<asp:Label ID='Label1' runat='server' Text='Age:'></asp:Label>
        
    					<asp:TextBox  id='TextBox2' Runat='Server' />
					<asp:Button ID='Button2'   ValidationGroup='Group2' Text='Submit'
						  OnClick='Group2Click'  Runat='Server' />
					<asp:RangeValidator ID='RangeValidator1' runat='server' ErrorMessage='Enter Age 
						   between 18 To 58'  MaximumValue='58' MinimumValue='18' 
						   ValidationGroup='Group2' ControlToValidate='TextBox2'>
					            Enter Age between 18 To 58</asp:RangeValidator>
				</fieldset>
        			</div>
    		</form>
	</body>
</html>
Permalink
How can the child controls be created in server controls?

Child controls can be created by overridding the CreateChildControl method as below

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebCustomControl1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server> </{0}:WebCustomControl1>")]
    public class WebCustomControl1 : WebControl
    {
        public TextBox txtname = new TextBox();
        public TextBox txtnum = new TextBox();
        [Bindable(true)]
        [Category("Appearance")]
        [DefaultValue("")]
        [Localizable(true)]
        public string Text
        {
            get
            {
                String s = (String)ViewState["Text"];
                return ((s == null) ? String.Empty : s);
            }
            set
                        {
                            ViewState["Text"] = value;
                        }
                }
        protected override void CreateChildControls()
        {
            Controls.Add(new LiteralControl("Name: "));
                            Controls.Add(txtname);
            txtname.Text = "";
            txtname.ToolTip = "Enter a Username";
            txtname.Attributes.Add("autocomplete", "off");
 
            Controls.Add(new LiteralControl("</br>"));
            Controls.Add(new LiteralControl("EmpNo: "));
            this.txtnum = new TextBox();
            Controls.Add(txtnum);
            txtnum.Text = "";
 
            txtnum.ToolTip = "Enter a Username";
            txtnum.Attributes.Add("autocomplete", "off");
            Controls.Add(new LiteralControl("</br>"));
 
        }
 
        protected override void RenderContents(HtmlTextWriter writer)
        {
            this.EnsureChildControls();
            this.RenderChildren(writer);
         }
        }
}
Permalink
How can you create a check box dynamically in the server control?
usingSystem;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Text;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;

namespace WebCustomControl1
{
	[DefaultProperty('Text')]
	[ToolboxData('<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>')]
	public class WebCustomControl1 : WebControl
	{
		[Bindable(true)]
		[Category('Appearance')]
		[DefaultValue('')]
		[Localizable(true)]
		public string Text
		{
			get
			{
				String s = (String)ViewState['Text'];
				return ((s == null) ? String.Empty : s);
			}
			set
			{
				ViewState['Text'] = value;
			}
		}
		
		protected override void CreateChildControls()
		{
			CheckBox blah = new CheckBox();
			blah.Text = 'CheckText';
			blah.ID = 'CheckValue';
			this.Controls.Add(blah);
		}
	
		protected override void RenderContents(HtmlTextWriter writer)
		{
			this.EnsureChildControls();
			this.RenderChildren(writer);
		}
    	}
}
Permalink
How can you write events for the server controls?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace WebCustomControl1
{
    [DefaultProperty("Text")]
    [ToolboxData("<{0}:WebCustomControl1 runat=server></{0}:WebCustomControl1>")]
    public class WebCustomControl1 : WebControl,IPostBackEventHandler
    {
        // Defines the Click event.
        public event EventHandler Click;
 
        //Invoke delegates registered with the Click event.
        protected virtual void OnClick(EventArgs e)
        {
 
            if (Click != null)
                        {
                Click(this, e);
                        }
        }
 
        // Define the method of IPostBackEventHandler that raises change events.
            public void RaisePostBackEvent(string eventArgument)
            {
                        OnClick(new EventArgs());
                }
 
            protected override void Render(HtmlTextWriter output)
            {
                    output.Write("<INPUT TYPE = submit name = " + this.UniqueID +  " Value = ’Click Me’ />");
                }
 
        }
}
Permalink
What is an Associated ControlID?

This is the property defined for a Label control in 2.0, which provides linking to an interactive control such as textbox,button,listbox and other asp.net controls. It defines a hot key which moves the input focus to the control defined in the property.

<asp:Label ID='Label1' runat='server' AssociatedControlID='TextBox1' Text='Enter Ur Details' 
 	Width='86px'></asp:Label>
<asp:TextBox ID='TextBox1' runat='server'></asp:TextBox>

In the above code, TextBox1 gets focused on clicking the Label1, sinced its AssociatedControlID is set to TextBox1.

Permalink
How can an ListItem in the ListControl can be avoided from being displayed but it must remain in the collection?

In ASP.NET 2.0 List by setting Enabled=’False’ to the individual list item, entries avoids it from being displayed but it remains in the collection.

It can be coded as below.

<asp:ListBox ID='ListBox1' runat='server' >
	<asp:ListItem   Enabled='False'>Item 1</asp:ListItem>
	<asp:ListItem>Item 2</asp:ListItem>
	<asp:ListItem>Item 3</asp:ListItem>
	<asp:ListItem>Item 4</asp:ListItem>
	<asp:ListItem>Item 5</asp:ListItem>
	<asp:ListItem>Item 6</asp:ListItem>
</asp:ListBox>

Here Item1 remains in the collection but will not be displayed.

Permalink
How can I check whether the file exists?

For all the File manipulation function the namespace System.IO; has to be included.

The existence of a file can be checked by the following syntax , File.Exists(path);
where path is the path of the file name.

The code can be as.

if(File.Exists('C:\\dict.txt'))
{
	Response.Write('File Exists');
}
else
{
	Response.Write('File Not Found');
}
Permalink
How can I include file through the ASPX?

The files can be included by the following syntax

<!--include file='filename'-->
<table>
	<tr>
		<td>
			<!--#include file='sample.html'-->
		</td>
	</tr>
</table>

Now the sample.htm will be displayed in the aspx page.

Permalink
How can ASPX pages been refreshed perdiodically?

The meta tag has to be include which automatically refresh the page every n second.

<meta http-equiv='Refresh' content='nn'>
Permalink
How can a ClientSideEvent can be attached to a Custom control?

We can add any ClientSideEvent like Onclick,OnBlur in the Render Method as,

protected override void Render(HtmlTextWriter writer)
{
	_button.Attributes.Add('OnClick','JavascriptClickFunction');
}
Permalink
How can the output cache can be enabled?

Output Cache can be enabled by the following line

<%@ OutputCache Duration='60'%>

This will make the page to be cached for 60 seconds.

Permalink
How can I use Tracing in Custom Components?

In Custom Components, you can use tracing if you reference the System.Web namespace and use the HttpContext.Current object to get a reference to the current context.

VB.NET

System.Web.HttpContext.Current.Trace('xxx', 'Message')

C#

System.Web.HttpContext.Current.Trace('xxx', 'Message');

Also make sure to set the following directives:

For Page Level Tracing set Page Directive as

<%@ Page Trace='true' %>

For Application Level Tracing modify corresponding web.config as

<configuration>
    <system.web>
        <trace enabled="true" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" />
    </system.web>
</configuration>
Permalink
What is being passed back and forth in the _ViewState form control?

The __VIEWSTATE hidden field is used to transfer the differences in controls from what is declared in the page — and the values they contain at the end of a request immediately prior to rendering. We can then use this information to re-construct the server controls to match that last rendered state during ‘postbacks’ to a page.

The information within the __VIEWSTATE field is not really encrypted — although the values are definitely ‘cyptic’ to read (mainly because server controls try to store information in as compact a format as possible — and because our serializer performs some limited compression).

You can see how much viewstate each control is saving by enabling tracing for the page. For example, by adding a trace attribute to the page directive:

<%@ Page Language='VB' Trace='True' %>

This will cause a table to be output at the bottom of the page. This won’t show the exact values stored in viewstate — but will give you a rough estimate of the size of each server control value.

Note that you can disable the viewstate feature — either for the entire page or on specific server controls. This is done at the page level by setting the following page directive:

<%@ Page Language='VB' MaintainState='False' %>

or on an individual server control by setting a ‘maintainstate’ attribute:

<asp:datagrid id='MyGrid1' maintainstate='false' runat=server/>
Permalink
How can we convert an ASP.NET page to HTML?

We can use the following codings to convert the ASP.NET page to HTML page,

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Net;
publicpartialclass_Default : System.Web.UI.Page
{
	WebRequest mywebRequest;
	WebResponse mywebResponse;
	StreamReader sr;
	string strHTML;
	StreamWriter sw;
	protected void Page_Load(object sender, EventArgs e)
	{
		mywebRequest = WebRequest.Create('http://www.syncfusion.com/Corporate/default.aspx');
		mywebResponse = mywebRequest.GetResponse();
		sr = new StreamReader(mywebResponse.GetResponseStream());
		strHTML = sr.ReadToEnd();
		sw = File.CreateText(Server.MapPath('temp.html'));
		sw.WriteLine(strHTML);
		sw.Close();
	}
}

Now the Html Code of (‘http://www.syncfusion.com/Corporate/default.aspx’) will be placed in the application folder by the name temp.html

Permalink
What is the difference between Session and ViewStates?

Sesseion is data stored per user session. ViewState is a way for the application to maintain state about a particular form and its child controls.

Permalink
When I run a page, I get the error ‘The page cannot be displayed’ and an HTTP 502 Proxy Error. Why?

This error can occur if you are running ASP.NET Web pages using the Visual Web Developer Web server, because the URL includes a randomly selected port number. Proxy servers do not recognize the URL and return this error.

To get around the problem, change your settings in Internet Explorer to bypass the proxy server for local addresses, so that the request is not sent to the proxy.

In Internet Explorer, you can make this change in Tools > Internet Options. In the Connections tab, click LAN Settings and then select Bypass proxy server for local addresses.

Permalink
How can a Multi-dimensional array be stored in session state and the values stored can be reterieved?

The below codings allow a multi-dimensional array to be stored in the session state

private void StoreToSession()
{
	string[,]initialArray={'A','B'};
	Session['sessionvalue']=initialArray;
}

private void ReteriveFromSession()
{
	string[,]resultantArray=(string[,])Session['sessionvalue'];
	TextBox1.Text=resultantArray[0,0].ToString();
	TextBox2.Text=resultantArray[0,1].ToString();
}
Permalink
How can I define a Hashtable to store session variable?

We can define a hashtable to store a session variable as

Session['sessionVaribale']=new Hashtable();

Then the values can be stored as

((Hashtable)Session['sessionVariable'])['hashKey']='value1';
Permalink
How can session expire time can be set?

The session will normally expire in 20 minutes.

To set the session expire time add the following code to Gloabl.asax

void Session_Start(object sender, EventArgs e) 
{
	Session.Timeout = 60;
}
Permalink
How do I insert custom @ Register tags into the aspx file from my custom control

In the custom control’s custom designer’s Initialize override, do something like this:

[C#]
public override void Initialize(IComponent component)
{

 	base.Initialize (component);

	IDesignerHost host = component.Site.Container as IDesignerHost;
 	IDesigner designer = host.GetDesigner(host.RootComponent);

 	// Calling GetHTMLFromWebControlTool with the following custom toolboxitem will insert the
 	// Register directives for the type associated with that .
 	MethodInfo mi = designer.GetType.GetMethod('GetHTMLFromWebControlTool', BindingFlags.NonPublic | BindingFlags.Instance);
 	if(mi != null)
	{
  		// DependantType is a custom type defined in DependantAssembly.dll
  		mi.Invoke(designer, new object[]{new WebControlToolboxItem(typeof(SomeNamespace.DependantType))});
 	}
}

Then when the user drags and drops the item from the toolbox, besides the default @ register entry it makes, it will also make an entry like this: <%@ Register TagPrefix=’cc1′ Namespace=’SomeNamespace’ Assembly=’DependantAssembly, Version=2.0.0.1, Culture=neutral, PublicKeyToken=3d6dfsd1fdsd44c89′ %>

The assembly will not be strong named in the above tag if it’s not in the GAC.

Permalink