Saturday, 30 August 2008

ASP.NET LinkButton without JavaScript

If you use ASP.NET LinkButton controls, the client browser must have JavaScript enabled. If JavsScript is disabled, clicking on the link won't cause a postback. To avoid this scenario, use standard Button controls and style them to look like hyperlinks.

Example:
<asp:Button runat="server" CssClass="HyperlinkButton" Text="Submit" />

CSS:
.HyperlinkButton
{
background: none;
border: none;
cursor: pointer;
text-align: left;
}

.HyperlinkButton:hover
{
text-decoration: underline;
}

Friday, 22 August 2008

How do I add a HTTP module in ASP.NET?

<?xml version="1.0"?>
<configuration>
<system.web>
<httpModules>
<add name="ModuleName" type="ClassName, AssembleyName" />
</httpModules>
</system.web>
</configuration>

Example:

<add name="URLRewriter" type="HTTPModules.URLRewriter, HTTPModules" />

How do I create controls at runtime in ASP.NET

If you want to create controls at runtime and render them, the LoadControl method should be used instead of doing a normal object declaration. This is the only way that child controls (within the control you want to create) will be instantiated. The LoadControl method accepts the virtual path to the control as a string (e.g. *.ascx file) or the type of control and it's arguements as an object array (pass in null if no arguements need to be supplied). The second overload can be used if the control is part of a class library.

Although you're creating an object of the control type, I wouldn't recommend doing the following because null reference exceptions will be thrown when any child control is referenced:
MyControl myControl = new MyControl();

These examples show how dynamically create controls correctly:

Example 1:

MyControl myControl = LoadControl( "MyControl.ascx" ) as MyControl;

if ( myControl != null )
{
// Do something.
}

Example 2:

MyControl myControl = LoadControl( typeof( MyControl ), null ) as MyControl;

if ( myControl != null )
{
// Do something.
}

I normally have a PlaceHolder indicating the position where I want this dynamic content:

phDynamicControls.Controls.Add( myControl );

HTML labels

HTML labels can be placed next to form controls as an indication of what they represent so the user has an idea of their expecated value(s). They can also be linked to an individual control using the for attribute. This means that when the user clicks on the label, the focus of the page will be set to the respective control.
<label for="name">
Name
</label>
<input type="textbox" name="name" id="name" />

Clicking on the label will set the focus to the input box.

Example:

How do I include browser specific CSS files?

Internet Explorer 6 and 7 respectively:
<!--[if lte IE 6]><link href="/css/IE6.css" rel="stylesheet" type="text/css" /><![endif]-->

<!--[if lte IE 7]><link href="/css/IE7.css" rel="stylesheet" type="text/css" /><![endif]-->