ASP / ASP.NET

Last Updated: 2001

Topics

General

Control Description
AdRotator Ad Rotator
Button General purpose button. Post button by default (?? although this might just be to insure the button is processed ??)
Calendar Calendar control (with date range selection capabilities)
CheckBox CheckBox (single)
CheckBoxList CheckBox (multiple)
DataGrid Can be connected to an ADO.NET data source (basically anything that implements ICollection interface, so we talking arrays as well as SQL result sets). See example below
DataList ??. Can be connected to an ADO.NET data source
DropDownList Combo box
HyperLink HyperLink
Image Image
ImageButton Button with image instead of text
Label Label
LinkButton HyperLink button
Panel ??
RadioButton Radio Button (single)
RadioButtonList Radio Button (multiple)
Repeater Include template code multiple times
Table Table
TextBox Textbox

These controls are referred to in code with the <asp: reference and require the runat=server setting. For example: <asp:Button id=myButton text=Submit runat=server /> (Page compiles find without runat=server, but the code behind the controls will not have been "expanded" by the server so are unlikely to do anything useful)

Examples

public DataTable GetData() {
    DataSet ds = new DataSet("myDataSet");
    DataTable dt;
    SqlDataAdapter sqlDA = new sqlDataAdapter(
        "select * from Employees",
        "server=myServer;user id = sa;password=;database=northwind");
    sqlDA.Fill(ds, "Employees");
    return ds.Tables["Employees"];
}

Then add the following code to the ASP page:
<%
    dg1.DataSource = GetData();
    dg1.DataBind();
%>
<asp:DataGrid AutoGenerateColumns=True runat=server id=dg1/>

Note: It took a long time to work this out as (a) All the beta 1 examples don't work with Beta 2 and (b) Beta 2 implementation of datasets/grids through ASP is very bugged. For example, if you move the dg1.DataSource/Bind code to after creation of dg1 is just doesn't do anything!

Back to Topic List 

Validation Controls

Control Description
CompareValidator Compares 2 controls (or one control and a constant value). Comparisions can be = =, >= etc.
CustomValidator UDF. There has to be a server side implementation (sure??), but a client side implementation can additionally be included (advanced clients will then use the client side validation and older clients the round trip to the validation on the server).
RangeValidator Check value is between a specified upper and lower boundary.Works with numbers, characters and dates.
RegularExpressionValidator Applies regular expression matching to validation
RequiredFieldValidator Checks field has been changed from initial value
ValidationSummary Calls all other validations on the page to ensure all pass. Those that fail have their associated ErrorMessage text values harvested and displayed in one grouping by the ValidationSummary control. Different text (e.g. a red *) can be displayed for the validated control by specifying the error message in ErrorMessage and the * in Text.

Examples:

<asp:RequiredFieldValidator ControlToValidate=txtName runat=server>You must supply a name!</asp:RequiredFieldValidator>

<asp:RangeValidator id="rangeTest" type="Integer" ControlToValidate = "txtMyControl" MaximumValue="30" MinimumValue="0" runat="server" />

<asp:RegularExpressionValidator id="exprTest" ControlToValidate="txtMyControl" ValidationExpression="^\d{3}$" Display="Static" runat="server">I was expecting 3 digits< asp:RegularExpressionValidator/>

Notes

Referencing Page.IsValid will cause all validation to be run. For example, writing "if (Page.IsValid) {o.text="Valid!"}; in code is fine (i.e. we don't have to call some sort of ValidatePage() function or each control's validation block first).

Referencing validator.IsValid is the same except obviously only that control's validation is re-evaluated. A useful trick is not to include any error message in the validator and in code check validator.IsValid and change a label manually.

 

Auto-PostBack

Events on the client that trigger code on the server tend to be postponed until the next submit. For example, place a listbox, a textbox and a button on a form. In the Page_Init add some enteries to the listbox. In the SelectedIndexChange of the listbox set the textbox's to display the current selection from the listbox. There is no need to do anything with the button.

Run the form. Change the listbox selection. Note that the textbox has NOT updated. Click the button. Even though the button has no code it has caused a postback and the textbox updated. Return to the editor and change the Listbox's AutoPostBack property to true. Run the form again. This time when the listbox is changed the textbox is automatically updated.

Back to Topic List 

 

<SCRIPT runat=server>...</SCRIPT> blocks vs. <%...%> blocks

To prevent confusion about when code embedded in an ASP.NET page is run <SCRIPT> blocks can only contain declarations, functions and methods while <%...%> blocks can only contain immediately executed code.

For example:

Allowed Not Allowed
<SCRIPT language=c# runat=server>
    int fred=3;
    public int myFunc(int z) {
      return z*fred;
    }
</SCRIPT>
<SCRIPT language=c# runat=server>
Response.Write("Never work");
</SCRIPT>
<%
    Response.Write("<b>Got Here<\b>");
%>
<% public void() donothing{} %>

This is different to ASP, where anything goes. Anecdotal evidence suggests this is a major cause of problems when converting ASP code to ASP.NET.

Back to Topic List 

 

Tricks & Tips
  • <%Response.Write(strCode);%> to write code when the page is fetched from the server, or just place code outside of <% %> marker (for example:
        <% for(int i=0; i<7; i++) { %>
            <font size ="<% =i.ToString()  %>"> Example </font><br>
        <%}%>
  • Session["strVariable"] to read/save values specific to that browser session
  • <input onclick="object.method()" type = "button" value = "Button Text"> to create a client-side button (e.g. to replay a media clip)
  • To obtain a reference to the selected item in a radio button group, oGroup.SelectedItem
  • To change page programmatically: Response.Redirect(strURL)
  • Request object can be used to refer to previous page values, e.g. Request.QueryString("control")
  • Properties in controls in a contained class can be set in <tags> by using "-" rather than ".". For example if "SomeTag" contains a format object which has a size property it can be accessed as <SomeTag Format-Size="10">
  • Use <%-- text --%> to create a comment block in a web page that (unlike <!-- text -->) won't be downloaded to the client. Doesn't appear to work in .js files.
  • [IE only] To ensure a particular control is in view when the page is (re)loaded on the client, add the following JScript to the page: ClientID.scrollIntoView();

Back to Topic List