ASP.NET Trips & Tricks

 

 

So here goes common tip and tricks:-

 

Adding Javascript Attributes

There are two ways to add Javascript attributes to a particular ASP.Net Server control:

button1.Attributes.Add("OnClick", "document.form1.txtName.focus();")

button1.Attributes("OnClick")="document.form1.txtName.focus();"

 

 

Password matching regular expression:-

Password must be at least 4 characters, no more than 8 characters,

and must include at least one upper case letter, one lower case letter,

and one numeric digit.

 

^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{4,8}$

 

To print certain areas of a page

Create a style sheet for printing purpose, normally by removing/hiding background colors, images....

After that include it with media="print", so that this style sheet will be applied while printing

 

<LINK media="print" href="styles/printStyle.css" type="text/css" rel="stylesheet">

 

to refresh a aspx page at regular interval:-

<meta http-equiv="refresh" content="10">

 

 

Adding a Print Button with Javascript

If you'd like to use an ASP.Net button for printing, all you need to do is :

Add this line to the Page_Load event

btnPrint.Attributes("onClick") ="javascript:window.print();"

Add a button to the page called 'btnPrint'

Technically, that's it, but, let's say you want to do something a little fancier, using DotNet. Then, add a subroutine (let's call it 'DoPrint'):

 

Sub doPrint(Source as Object, E as EventArgs)

            lblResults.visible="True"

            lblResults.text="Page has successfully been sent to the printer!"

End Sub

Then, add a direction to this sub, in the button's tag:

onServerclick="doPrint"

 

 

 

Assigning ASP.Net variables to Javascript

Scenario: you have an ASP.Net variable called sCustState, that you also want to use in a Javascript function. Here's how you do make it work, within Javascript, assigning it to a Javascript variable.

 

var sstate;

sstate='<%#sCustState %>';

 

  

Allow numerics for textbox

 

<asp:CompareValidator runat="server"

            id="CompareValidator1"

            Operator="DataTypeCheck"

            Type="Integer"

            ControlToValidate="TextBox1"

            ErrorMessage="Enter numeric value." />

 

clear all text boxes

 

Control myForm = Page.FindControl("Form1");

foreach (Control ctl in myForm.Controls)

if(ctl.GetType().ToString().Equals("System.Web.UI.WebControls.TextBox"))

((TextBox)ctl).Text = "";

 

This will clear EVERYTHING from the textboxes - even if you had them pre-populated with data. A VERY simple way to just reset it to the condition at Page_Load time, just do this in the Reset SubRoutine:

Server.Transfer("YourPageName.aspx")

 

 

Color Picker in ASP.NET

Microsoft has confirmed a bug, saying that the attributes property of ListItem will not work in the DropDownlist(i.e Web server Control). The alternative for this is to use HTML Server Control

So we then would do is as below:

<SELECT id="DropDownList1" name="DropDownList1" runat="server">

</SELECT>

Using this control we'll change the background Color of each Item in DropDown.

private void Page_Load(object sender, System.EventArgs e)

{

            // Put user code to initialize the page here

            if (!IsPostBack)

            {

            foreach(FieldInfo col in typeof( KnownColor).GetFields() )

            {

            if (col.FieldType == typeof(KnownColor) )

                        {

                        DropDownList1.Items.Add(new ListItem(col.Name ,col.Name));

                        }

            } 

}

            for (int i= 0 ;i < DropDownList1.Items.Count;i++)

            {

            DropDownList1.Items[i].Attributes.Add("style", "background-color:" + DropDownList1.Items[i].Text);

            }

}

 

Make sure to Import the System.Reflections namespace, as well as the System.Drawing namespace, for this example

 

This is end  for part-1(also i ll suggest and request our members to contribute more)

 

 

Cookieless session problems

If you have tried to implement cookieless sessions in ASP.NET and haven't been able to make it work, the following is likely your problem.

 

 

1.   Fully qualified URLs in the response.redirect, server.transfer, and FORM action

     tags cannot be used.  Here is an example of a fully qualified

     URL:  https://www.eggheadcafe.com/default.asp

 

2.   Root addressing can also cause problems with response.redirect,

     server.transfer, and FORM action tags.   In other words /home/default.aspx

     cannot be used.   You'd have to reference it using relative addressing.

     For example, home/default.aspx

 

It is still ok to use root addressing or fully qualified URLs for things like

JavaScript files and images.   You just have to use relative addressing

for links locally on your site.   I entered this Tip because most ASP.NET

books only specifically mention #1.

 

 

 

 

xxxxxxx

Somtimes you get "Access Denied" error when compiling .NET project, or similar message.

  I've found there are several likely causes:

 

1) You get the error "Could not copy temporary files to the output directory" when compiling a VB.NET or C# project from inside Visual Studio.  

 

The target EXE or DLL file is running or is being used by another application (for example, you are using ILDASM to explore the IL code it contains.  You must close the running application to release the lock.

 

2) Another VS project has a reference to the assembly you're attempting to compile and the Copy Local property of the reference is set to False.  In this case the VS project has a direct reference to your assembly (instead of creating a copy in that project's directory) and  locks the file.  In this case solve the problem by setting the Copy Local property to True (the default value).  

 

3) I have found that turning off the Indexing Service (shut off and set to Manual) in Services Control Panel Applet) solved the "add assembly *" error with Access Denied.   Most people don't need Indexing Service anyway, so you'll find you've done yourself a favor as your machine will use less memory.

 

 

 

 

File download from a page

<%@ Page language="C#" debug="true" %>

<script language="C#" runat="server">

private void Page_Load(object sender, System.EventArgs e) {

   Response.ContentType="application/zip";

            Response.AppendHeader("Content-Disposition","attachment; filename=myzipfile.zip");

            Response.WriteFile(@"c:\inetpub\wwwroot\myzipfile.zip");

            Response.Flush();

}

</script>

 

N.B.  <st1:place w:st="on"><st1:PlaceName w:st="on"><u1:place u2:st="on"><u1:PlaceName u2:st="on">Reader</st1:PlaceName></u1:PlaceName> <st1:PlaceName w:st="on"><u1:PlaceName u2:st="on">Shaun</st1:PlaceName></u1:PlaceName> <st1:PlaceName w:st="on"><u1:PlaceName u2:st="on">College</st1:PlaceName></st1:place></u1:PlaceName></u1:place> added the following to chop off the extra junk that may be sent by the ASP.NET runtime along with your file:

 

Response.AddHeader ("Content-Length", FileSize.ToString());

 

 

SESSSION_END not firing:-

If the code you've entered in your Global.asax file to run when the Session End event fires doesn't appear to be kicking in, there are just three things that could be at fault:

 

You're not using InProc—The mode attribute of the <sessionState> element in your application Web.config file must be set to "InProc". If it isn't, the End event simply cannot fire.

You're not using the Session—The Session End event can't fire if there's no Session to End. Are you sure your application is storing information through the Session object?

Your code is flawed—There's an error somewhere in the code that responds to the End event. Try running your application in debug mode, with a short <sessionState> timeout attribute. Visit the page and then wait. Does the End event kick in? Does an error occur in your code?

There is quite seriously no other excuse for your code not running. There's no mysterious bug. There are no weird setup issues or reasons for not trusting the Session End event. It works, no excuses.

 

 

 

 Can a user browsing my Web site read my Web.config or Global.asax files?

 

No. The <httpHandlers> section of Machine.config, which holds the master configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file.

 

 What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript?

 

RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs.

 

 

Codegen path

 

When you visit an ASP.NET page, the .aspx source file is parsed and compiled to an assembly automatically linked to

 the application. The assembly is given a random generated name and is stored in temporary folder on the

local disk.  

The exact path to this folder is returned by the following call.

 

string path = HttpRuntime.CodegenDir; 

If you set the Debug attribute to True in the Page directive,

in the same folder you also find the VB or C# source code that is then compiled.  

%@Page ... Debug="True"

 

The language of the source depends on the language set for the page.

 

 

 

prevent caching of webform :-

 

Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.Cache.SetAllowResponseInBrowserHistory(false);  

Add above two lines of code in the Page_Load 

 

default button:-

 

How to make a button Default Button?

public static void MakeDefault(System.Web.UI.Page oPage, TextBox oTxt, ImageButton oBtn)

 

{

      StringBuilder sb = new StringBuilder();

      sb.Append("<SCRIPT language='javascript'>");

      sb.Append("function fnTrapKD(btn){");

      sb.Append(" if (document.all){");

      sb.Append("   if (event.keyCode == 13)");

      sb.Append("   { ");

      sb.Append("     event.returnValue=false;");

      sb.Append("     event.cancel = true;");

      sb.Append("     btn.click();");

      sb.Append("   } ");

      sb.Append(" } ");

      sb.Append("}");

      sb.Append("</SCRIPT>");

 

      oTxt.Attributes.Add("onkeydown", "fnTrapKD(document.all." + oBtn.ClientID + ")");

 

      oPage.RegisterStartupScript("ForceDefaultToScript", sb.ToString());

 

}

 

To call above function

DefaultButton(Page, TextBox1, Button1)

 

Your Field Name] is neither a DataColumn nor a DataRelation for table [Your Table Name].

If you're getting this message and you know beyond a shadow of a doubt that this field/column DOES, indeed, exist in your table, then, check your SQL query to make sure you included the field name in the query.

(Most likely, it was forgotten)

The two possible reasons are that, either it doesn't exist in the table, or it doesn't exist in the SQL query.

check that the column name is not database generated. If you have a query like

select isnull(some_col, 0)... 

then you need to change it to 

select isnull(some_col, 0) as some_col 

if you want to refer to 'some_col' in your code, otherwise you will still get this error.  

 

Add Item to Bound DropDownList

To add an item to the top of a DropDownList at any time, here's the code:

MyDDL.items.insert(0,"WhateverYouWantHERE")

 

The '0' shows that it needs to insert the item at the top position of the DropDownList item collection. The second part, "WhateverYouWantHERE" is the actual text you want displayed. You could also use this to put a blank item at the top:

MyDDL.items.insert(0,"")

or to specify both value and text:

Dim liItem as ListItem=New ListItem("text", "value")

MyDDL.Items.Insert(0, liItem) 

 

Adding a MailTo Link inside a DataGrid

Suppose you have a database table which contains an email field, and you'd like to display that field, as well as others in a DataGrid. Let's go one step further - - let's say you'd like to display that email field as a clickable MailTo link. One way that this can be easily be done using TemplateColumns. First, you create your DataGrid start and end tags. Then, inside these tags, you include 'Columns' start and end tags. That's where you put your TemplateColumn. Here's how to do it:

<Columns>

<i>.....Put any other boundcolumns you want inside here also</i>

            <asp:TemplateColumn HeaderText="Email Address" HeaderStyle-Font-Bold="True">

                        <ItemTemplate>

                                    <A HREF="Mailto:<%# Container.DataItem("email") %>">

                                                <%# Container.DataItem("email") %>

                                    </a>

                        </ItemTemplate>

            </asp:TemplateColumn>

</Columns> 

 

ASP.Net Server Controls Not Showing on pages

It's possible that ASP.Net is not registered correctly on your system.

Try running aspnet_regiis from the command prompt.

 

Here's the default location:

 

C:\WINNT\Microsoft.NET\Framework\<<ASP.Net Version#>>\aspnet_regiis.exe -i

 

Windows Server 2003, you must use aspnet_regiis -i -enable

This is because of the "Web Service Extensions" feature in IIS 6

(if you install VS.NET or the framework without IIS installed, and then go back in and install IIS afterwards, you have to re-register so that ASP.NET 'hooks' into IIS properly."

 

 

 

AllowCustomPaging must be true and VirtualItemCount must be set

If you are getting this error:

'AllowCustomPaging must be true and VirtualItemCount must be set for a DataGrid with ID MyDataGrid when AllowPaging is set to true and the selected datasource does not implement ICollection'

Most likely, you are trying to implement paging in a DataGrid while binding the DataGrid with a DataReader.

To fix this, instead of using a DataReader to bind data to the DataGrid, use a DataSet

 

Could not find installable ISAM

If you are using the OleDb Managed Provider, and you get this error, double check your connection string, to see if everything is spelled correctly. For instance, if you use 'DataSource' instead of 'Data Source', or misspell any other key words in the string, you will get this error.

Also - when all else fails, check out this MS link:

https://support.microsoft.com/?scid=kb;EN-US;209805

 

DropDownList doesn't work when clicking currently selected item

 

Let's say you populate your dropdown list with five items.By default, the top item is 'selected' or showing, when the population finishes. Then, if you choose that item in a that is currently showing, it won't fire the onselectedindexchanged event. That's because it's not a click event. The item in the DropDownList actually needs to change to fire this event.

 

The way to get around this is to add a 'dummy' item to the top of the list, once it's populated, like:

" -- Choose -- "

Then, any valid item you choose from there should work. The only drawback is that you need to code around this item in your event procedure, like this:

 

If ddl.SelectedItem.text <> " -- Choose -- " then

    'put code for event here

End if

 

Calculate Age from Your BirthDate

First, you need a text box called txtBirthDate.Text, a button and a Label called lblShowAge.Text The code for the button's click event should read:

Dim CurrentDate as DateTime = DateTime.Today()

Dim BirthDate as DateTime

            ' Makes sure the text input is converted to a Date:

BirthDate = CDate(txtBirthDate.text)

Dim diff as TimeSpan  = CurrentDate.Subtract(BirthDate)

            '    'Cint' Converts the output to an Integer (no decimal places)

lblShowAge.text=Cint(diff.Days/365)

 Conditional Javascript - Setting Javascript Focus - Inline Coding

 

One of the 'gotchas' about inline coding is that, within a script tag, you can not have another script tag. On the surface that sounds reasonable.

 

However, let's say, you have some conditional coding, in within that coding, you want to place focus in another textbox, using Javascript. Normally, you'd probably do something like this:

response.write("<script>document.form1.txtLname.focus();</script>")

 

The problem occurs when ASP.Net reads that closing script tag. It reads it as the close of it's main Script tag.

 

To get around this and not confuse ASP.Net, you can do it like this:

response.Write ("<" & "script>document.form1.txtLoanNum.focus();<" & "/script>")

 

Create a Printer Friendly page (no Headers or Footers)

So, you've got this great dynamic page, with user controls for your header and your footer, but you need to have the ability for the end-user to have a print-out without the header and the footer.

One way to accomplish this would be to have your content section, completely in a User Control also. That way, you could just create a blank page, and put the user control there. From the original page, just link to this new blank page. All you'll see is the content.

Then, you can use the Javascript Print Function for printing.

Inlude an ASP button Server Control in your new Print-Friendly page, called 'btnPrint'. Then, in the Page_Load event, type in:

btnPrint.Attributes("onClick") ="javascript:window.print();"

Voila! - that's all there is to it. You can get fancier, if you'd like, actually adding an 'OnServerClick' sub, so that you could use ASP.Net to return a 'Successful Print' message...from this point on, it's up to you on how you'd like to customize this!

 

Currently logged in user

To get the user ID of the user who is currently logged in, you would get it using this: System.Web.HttpContext.Current.User.Identity.Name

 

Get windows Identity(win auth)

System.Security.Principal.WindowsIdentity.GetCurrent().Name.ToString();

 

Could Not Load type (namespace.filename) error

If you are using VS.Net, in the Page Directive's Inherits property, it normally puts it in this format:

Inherits = "Namespace.Webform1"

When you get this error, try removing the Namespace and the period between the two.

Also, add the Src property, duplicating the page in the CodeBehind property. The CodeBehind property is for VS.Net, so if you are continuing to edit in VS.Net, you should not remove it.

 

Disabling a Button Until Processing is Complete

 

Here's the scenario - let's say you have an Insert subroutine, called 'doInsert'. You want to immediately disable the Submit button, so that the end-user won't click it multiple times, therefore, submitting the same data multiple times.

 

For this, use a regular HTML button, including a Runat="server" and an 'OnServerClick' event designation - like this:

<INPUT id="Button1" onclick="document.form1.Button1.disabled=true;" type="button" value="Submit - Insert Data" name="Button1" runat="server" onserverclick="doInsert">

 

Then, in the very last line of the 'doInsert' subroutine, add this line:

Button1.enabled="True"

 

RollOver Form

<meta http-equiv="Page-Exit" content="progid:DXImageTransform.Microsoft.Fade(duration=.9)">

 

 

Force Button Click by Pressing Enter Key

Sometimes, you will notice, that, in an ASP.Net form, depending on the circumstances, pressing the 'Enter' key to submit the form does not work.

 

To force this to happen for a particular button on your page, just put this in the Page_Load routine:

Page.RegisterHiddenField("__EVENTTARGET", "button1")

Then, change 'button1' to the ID of your particular button. Understand, of course, if your cursor is inside of a MultiLine textbox, the default action of the enter key is to create a new line in the textbox, so, if this basically works anywhere outside of that scenario.

 

How to open a new web page with a button click

You can use Javascript to do so.

e.g.

<input type="Button" Value="Open New" onclick="Javascript:window.open('webform1.aspx');">

 

 

How to set focus on an ASP.Net TextBox Control when the page loads

Option:-1

Two things:

1. Give your BODY Tag and ID and include 'Runat=Server'

(like - - <body id="bdyMain" Runat="Server">)

2. In the Page_Load event:

if not Page.IsPostBack then

            bdyMain.attributes("onload")="document.form1.TextBox1.focus();"

end if

 

//Option2:-

function window_onload()

{

            document.getElementById("<st1:City w:st="on"><st1:place w:st="on">ur</st1:place></st1:City> control ID").focus();

}

 

 

 

ItemStyle/HeaderStyle Properties not working with DataGrid

 

Remember that a DataGrid generates an HTML Table, with TableRows and Cells. If you have ItemStyle/HeaderStyle/SelectedItem/FooterStyle tags with display properties (like forecolor/bold/font properties) and some of them are not displaying like you think they should, be sure to check your page for a StyleSheet.

If you have a TD tag section in your page's stylesheet - -whatever properties you set there will normally override whatever you add into your DataGrid's Item styles.

 

 

Javascript - Delete Textbox text onFocus

Let's say you have an ASP.Net TextBox server control that has the text:

"Enter Fax #"

Then, you want the text to disappear when the user clicks inside the TextBox - - here is a very simple solution.

In the Page_Load event, put:

txtFax.Attributes("OnFocus")="document.formName.txtFax.value='';"

 

 

 

Loop through all or certain type of controls on the ASP.NET Page

You can loop through all or certain type of controls on ASP.NET Page using this code. Code will loop through also those controls that are contained in some other container that Form, Panel for example. Example of looping through all TextBoxes on Page.

 

[C#]

private void LoopTextBoxes (Control parent)

                        {

                                    foreach (Control c in parent.Controls)

                                    {

                                                TextBox tb = c as TextBox;

                                                if (tb != null)

                                                            //Do something with the TextBox

 

                                                if (c.HasControls())

                                                            LoopTextBoxes(c);

                                    }

                        }

 

 

 

 

 

Javascript Window Open Method with Hyperlink Control

Instead of merely using an ASP.Net Hyperlink control to link to another page, you can mix in the Javascript Window.open method, just like you did in Classic ASP - like this:

<asp:Hyperlink id="mylink" NavigateURL="javascript:window.open ('faqs.html','Info','width=500,height=400,toolbar=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes');" Text="Click Me" runat="server" />

(Where 'faqs.html' is your own file name)

 

 

 

Make Window Fit any Resolution

This will make the current page fill the entire screen, at whatever resolution the client is using. You can put a reference to this in the Body tag, making a function out of it and using the 'onload' call, or you can just put it directly in the page:

<script language="Javascript">

            UserWidth = window.screen.availWidth;

            UserHeight = window.screen.availheight;

            window.resizeTo(UserWidth, UserHeight);

            window.moveTo(0,0)

</script>

 

Make sure, though, that you are not using any fixed-width tables, as, even though the browser window will be full screen, scrolling will still be necessary, if the tables' widths are wider than the screen.

 

 

 

Convert Textbox Data to UpperCase

In order to do this, as it's typed, you must add a Javascript attribute to the Textbox.

 

 

 

In your Page_Load routine, assuming your text box's ID is 'TextBox1':

 

TextBox1.attributes("onKeyUp")="this.value=this.value.toUpperCase();"

 

 

Trimming string in javascript:

 

Trim ------ myString.replace( /^\s+/g,'').replace(/\s+$/g,'')

Strip Leading ---------- myString.replace( /^\s+/g,'')

Strip Trailing ----------  myString.replace( /\s+$/g,'')

 

 

 

Javascript OK/CANCEL alert

 

Here's a quick little example of how to capture the standard windows Ok/Cancel message box return value.

 

<HTML>

<SCRIPT language=JavaScript>

 

    function MsgOkCancel()

    {

      var fRet;

      fRet = confirm('Are you sure?');

      alert(fRet);

    }

 

</SCRIPT>

<BODY>

   <a href=javascript:MsgOkCancel(); >test me</a>

</BODY>

</HTML>

 

 

 

There are times when we are working with JavaScript and just can't remember the exact object name.   Here's a little snippet to stick in your code that will allow you to iterate through the object model and stop when you've found what you need.

 

  var oCtrl;

  try {

       for (oCtrl in document)

       { if (confirm(oCtrl) == false) { break;}}

      }

  catch(everything)  { alert('error found');  }

 

 

 

 

Many developers have asked how to use images to submit forms.

 

 Of course, the "input" tag allows this.   However, we often times want to submit the form differently depending on which image button was clicked.  

 

Here's a little sample function to demonstrate how to perform this task in JavaScript.   This sample shows you how to send a different querystring variable for which you can react to when the page is posted either to itself or another page.

 

 

<input type=image src=/images/EditAccount.jpg border=0>

<a href=javascript:EditAccount('1'); ><img name=EditAccount1 src=/images/EditAccount1.jpg border=0></a>

<a href=javascript:EditAccount('2'); ><img name=EditAccount2 src=/images/EditAccount2.jpg border=0></a>

 

  <SCRIPT