Wednesday, June 30, 2010

Difference between <>NULL/!=NULL/==NULL and IS NOT NULL/IS NULL

Consider following 2 queries:

1. SELECT * FROM Emp WHERE MiddleName <> NULL
2. SELECT * FROM Emp WHERE MiddleName IS NOT NULL

Are the above 2 queries same? If not then what is the difference?

The difference in two queries lies in terms of how SQL Server interprets two queries and executes it at back end. The comparison operator "<>"can only be used with the valid data/ value and NULL doesn’t qualify as any data type and there is no memory location for NULL (practically SQL Server allocates 0 bytes for NULL).
Therefore with the first query, SQL Server will fail to compare the middle name with any values and hence the query will return 0 rows even if table has some NOT NULL values. But please not that there is no error thrown by the SQL Server which is contrary to Oracle.Second query would return all the rows where Middle Name is not null.

Courtesy Pramod and Sandeep

Monday, June 28, 2010

What Is CSS?

Cascading Style Sheets (CSS) is a style sheet language used to describe the presentation semantics (that is, the look and formatting) of a document written in a markup language. It’s most common application is to style web pages written in HTML and XHTML, but the language can also be applied to any kind of XML document, including SVG and XUL.

With CSS we can do

  • Enable the separation of document content (written in HTML or a similar markup language) from document presentation, including elements such as the layout, colors, and fonts. This separation can improve content accessibility, provide more flexibility and control in the specification of presentation characteristics,
  • Enable multiple pages to share formatting, and reduce complexity and repetition in the structural content.
  • CSS can also allow the same markup page to be presented in different styles for different rendering methods, such as on-screen, in print, by voice and on Braille-based, tactile devices.
  • CSS specifies a priority scheme to determine which style rules apply if more than one rule matches against a particular element. In this so-called cascade, priorities or weights are calculated and assigned to rules, so that the results are predictable.
  • Styles are normally saved in external .css files. External style sheets enable you to change the appearance and layout of all the pages in a Web site, just by editing one single file!
CSS Syntax

A CSS rule has two main parts: a selector, and one or more declarations:

selector { property: value; property: value; property: value……. }

The selector is the (X)HTML element that you want to style. The property is the actual property title, and the value is the style you apply to that property.

Each selector can have multiple properties, and each property within that selector can have independent values. The property and value are separated with a colon and contained within curly brackets. Multiple properties are separated by a semi colon. Multiple values within a property are separated by commas, and if an individual value contains more than one word you surround it with quotation marks. As shown below.

body
{
  background: #eeeeee;
  font-family: "Trebuchet MS", Verdana, Arial, serif;
}

As you can see in the above code I have separated the color from the font-family with a semi-colon, separated the various fonts with commas and contained the "Trebuchet MS" within quotations marks. The final result sets the body color to light grey, and sets the font to ones that most users will have installed on there computer.

You can combine elements within one selector in the following fashion.

h1, h2, h3, h4, h5, h6
{
  color: #009900;
  font-family: Georgia, sans-serif;
}

As you can see in the above code, I have grouped all the header elements into one selector. Each one is separated by a comma. The final result of the above code sets all headers to green and to the specified font. If the user does not have the first font I declared it will go to another sans-serif font the user has installed on their computer.

CSS Id and Class

In addition to setting a style for a HTML element, CSS allows you to specify your own selectors called "id" and "class".

The id Selector
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".
The style rule below will be applied to the element with id="para1":
Example

#para1
{
text-align:center;
color:red;
} 

The class Selector
The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for any HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
In the example below, all HTML elements with class="center" will be center-aligned:
Example
.center {text-align:center;} 

Three Ways to Insert CSS
There are three ways of inserting a style sheet:

  • External style sheet
  • Internal style sheet
  • Inline style
External Style Sheet
An external style sheet is ideal when the style is applied to many pages. With an external style sheet, you can change the look of an entire Web site by changing one file. Each page must link to the style sheet using the <link> tag. The <link> tag goes inside the head section:

<head>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
</head>

An external style sheet can be written in any text editor. The file should not contain any html tags. Your style sheet should be saved with a .css extension. An example of a style sheet file is shown below:

hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}

Do not leave spaces between the property value and the units! "margin-left:20 px" (instead of "margin-left:20px") will work in IE, but not in Firefox or Opera.

Internal Style Sheet
An internal style sheet should be used when a single document has a unique style. You define internal styles in the head section of an HTML page, by using the <style> tag, like this:

<head>
<style type="text/css">
hr {color:sienna;}
p {margin-left:20px;}
body {background-image:url("images/back40.gif");}
</style>
</head>

Inline Styles
An inline style loses many of the advantages of style sheets by mixing content with presentation. Use this method sparingly!
To use inline styles you use the style attribute in the relevant tag. The style attribute can contain any CSS property. The example shows how to change the color and the left margin of a paragraph:

<p style="color:sienna;margin-left:20px">This is a paragraph.</p>

Multiple Style Sheets
If some properties have been set for the same selector in different style sheets, the values will be inherited from the more specific style sheet.
For example, an external style sheet has these properties for the h3 selector:
h3
{
color:red;
text-align:left;
font-size:8pt;
}

And an internal style sheet has these properties for the h3 selector:

h3
{
text-align:right;
font-size:20pt;
}

If the page with the internal style sheet also links to the external style sheet the properties for h3 will be:

color:red;
text-align:right;
font-size:20pt;

The color is inherited from the external style sheet and the text-alignment and the font-size is replaced by the internal style sheet.

Multiple Styles Will Cascade into One

Styles can be specified:

  • inside an HTML element
  • inside the head section of an HTML page
  • in an external CSS file
Even multiple external style sheets can be referenced inside a single HTML document.

Cascading order
What style will be used when there is more than one style specified for an HTML element?
Generally speaking we can say that all the styles will "cascade" into a new "virtual" style sheet by the following rules, where number four has the highest priority:
  • Browser default
  • External style sheet
  • Internal style sheet (in the head section)
  • Inline style (inside an HTML element)
So, an inline style (inside an HTML element) has the highest priority, which means that it will override a style defined inside the <head> tag, or in an external style sheet, or in a browser (a default value).

Note: If the link to the external style sheet is placed after the internal style sheet in HTML <head>, the external style sheet will override the internal style sheet!

Friday, June 25, 2010

What are Ranking Functions?

This is in continuation of my last post Sql Server Rownumber

They are used within the column list of a query to create a new column containing an integer value for each row in a set of results. For example, the Row_Number() function generates a unique, sequential number for each row. Other functions may generate duplicate values depending upon their usage and the data they are operating against.

MSDN says, "Ranking functions return a ranking value for each row in a partition. Depending on the function that is used, some rows might receive the same value as other rows. Ranking functions are nondeterministic."

In simple terms, ranking functions allow you to sequentially number your result set. Your result set can be partitioned so the numbering essentially resets for each partition for example you can get the sales rank of employees partitioned by their department, or manager etc..

Transact-SQL provides the following ranking functions:
  • RANK
  • NTILE
  • DENSE_RANK
  • ROW_NUMBER
Row_Number
This function generates a unique integer value for every row in the results. The first row is assigned a value of one and each subsequent row increments the number. The syntax for this function is interesting as it introduces a new clause that will be seen in all of the ranking functions:

SELECT row_number() OVER (ORDER BY column-name), columns FROM table-name

The OVER clause specifies the order of the rows that should be used when generating values with the ranking function. Following the OVER keyword, the sort order to apply is provided in parentheses.

Rank
The results are ranked according to the sort order, with each row being given a number that is one greater than the number of results that appear before it. Where there are two or more items that are equivalent in the sort order they are each given the same rank. For example, if the first two items in the list are equivalent, they are both given a rank of one. The next item in the list will have a rank of three.

RANK ()    OVER ( [ < partition_by_clause > ] < order_by_clause > )

The rank of a row is one plus the number of ranks that come before the row in question.

Dense_Rank
The Dense_Rank function is very similar to Rank. The key difference is that there are no gaps between the rank values when duplicates are encountered. If the first two values in the sort order are identical, each will be given a value of one. The third value would have a dense rank of two, not three.

DENSE_RANK ()    OVER ( [ <partition_by_clause> ] < order_by_clause > )

The rank of a row is one plus the number of distinct ranks that come before the row in question.

Ntile
Is used to distribute the rows in an ordered partition into x number of groups. Each row receives the group number it belongs to.

The Ntile function splits the results of a query into a number of groups. Each group is then given a number that is applied to every row within the group. The numbering starts with group one and is incremented for every additional group. The syntax for the statement is similar to that of the previous functions with the addition of a parameter to specify the number of groups that should be generated.

TILE (integer_expression)    OVER ( [ <partition_by_clause> ] < order_by_clause > )

integer_expression

Is a positive integer constant expression that specifies the number of groups into which each partition must be divided. integer_expression can be of type int, or bigint.
Where possible, each group will contain exactly the same number of rows. However, if the number of rows is not divisible by the number of groups, the later groups will be one row smaller than the first group.

All together
the ROW_NUMBER function assigns a unique (and ascending) value to each row without regard for ties in the ORDER BY values, the RANK and DENSE_RANK functions assign the same value to rows that have the same ORDER BY value.  The difference between the RANK and DENSE_RANK functions is in how values are assigned to rows following a tie.

The easiest way to illustrate the difference between all of these functions is with a simple example:

CREATE TABLE T (PK INT IDENTITY, A INT, B INT, C INT)
CREATE UNIQUE CLUSTERED INDEX TPK ON T(PK)

INSERT T VALUES (0, 1, 6)
INSERT T VALUES (0, 1, 4)
INSERT T VALUES (0, 3, 2)
INSERT T VALUES (0, 3, 0)
INSERT T VALUES (1, 0, 7)
INSERT T VALUES (1, 0, 5)
INSERT T VALUES (0, 2, 3)
INSERT T VALUES (0, 2, 1)

SELECT *,
    ROW_NUMBER() OVER (ORDER BY B) AS RowNumber,
    RANK() OVER (ORDER BY B) AS Rank,
    DENSE_RANK() OVER (ORDER BY B) AS DenseRank
FROM T

PK    A     B     C     RowNumber  Rank       DenseRank
----- ----- ----- ----- ---------- ---------- ----------
5     1     0     7     1          1          1
6     1     0     5     2          1          1
1     0     1     6     3          3          2
2     0     1     4     4          3          2
7     0     2     3     5          5          3
8     0     2     1     6          5          3
3     0     3     2     7          7          4
4     0     3     0     8           7         4

Notice how the ROW_NUMBER function ignores the duplicate values for column B and assigns the unique integers from 1 to 8 to the 8 rows while the RANK and DENSE_RANK functions assigns the same value to each of the pairs of duplicate rows.  Moreover, notice how the RANK function counts the duplicate rows even while it assigns the same value to each duplicate row whereas the DENSE_RANK function does not count the duplicate rows.  For example, both the RANK and DENSE_RANK functions assign a rank of 1 to the first two rows, but the RANK function assigns a rank of 3 to the third row - as it is the third row - while the DENSE_RANK function assigns a rank of 2 to the third row - as it contains the second distinct value for column B.  Note that the maximum value returned by the DENSE_RANK function is exactly equal to the number of distinct values in column B.
Download Article

Thursday, June 24, 2010

SQL Server ROW_NUMBER

Suppose there is a table Students having the columns StudName, RollNo, TotalMarks.Write a query (in SQL Server) that returns RollNo, Student Name and Total Marks along with the position (based on marks) of the students in the class.
For eg. Suppose table has following records:


The output should be

INSERT INTO [ASPState].[dbo].[Students] ([StudName],[RollNo],[TotalMarks]) VALUES ('212094', 'X', 600)
INSERT INTO [ASPState].[dbo].[Students] ([StudName],[RollNo],[TotalMarks]) VALUES ('212095','Y', 540)
INSERT INTO [ASPState].[dbo].[Students] ([StudName],[RollNo],[TotalMarks]) VALUES ('212096','Z', 580)
INSERT INTO [ASPState].[dbo].[Students] ([StudName],[RollNo],[TotalMarks]) VALUES ('212097','A', 200)
INSERT INTO [ASPState].[dbo].[Students] ([StudName],[RollNo],[TotalMarks]) VALUES ('212098', 'B', 620)

Answer
SELECT *, ROW_NUMBER() OVER (ORDER BY TotalMarks DESC) AS StudPosition FROM Students

Tuesday, June 22, 2010

Keyboard Shortcuts for c#

Navigation
Ctrl+Tab Switch documents
Ctrl+Shift+Tab Reverse switch documents
Ctrl+kk Drop a bookmark
Ctrl+kn Itterate through bookmarks
F7 Switch from HTML to Codebehind view
Shift+F7 Switch from Codebehind to HTML view
Ctrl+- Navigate backward through last cursor locations
F12 Goto Definition
Ctrl+] Jump to matching brace

Editing
Ctrl+c Copy a whole line
Ctrl+v When a whole line in the clipboard (as above) this will instet a whole copied line.. handy for quick duplication
Ctrl+u Change to lower case
Ctrl+Shift+U Change to UPPER case

Macros
Ctrl+Shift+R Record a quick Macro
Ctrl+Shift+P Run the quick Macro you just recorded

Comments
Ctrl+kc Comment out selected lines
Ctrl+ku Uncomment selected lines

Formatting
Ctrl+kd Autoformat selected lines

Release vs. Debug Mode

When you compile your application in release mode debug information is not generated and this is the option normally used when you want to deploy your application to client.debug mode is heavy since debugging info gets generated and is used while development to find out error in your code.

When we are moving code to production then we make the mode as Release. Because there no debug is required and the execution also very fast in this mode due to the .pdb file formation will not happens.
You use the Debug and Release settings to control what happens when you build your application. You should use the Release setting when you're building for production and will not need to debug the application. When you build the application in Release mode, the debug symbols are not baked into the assembly, so you cannot debug it using Visual Studio .NET or other source code debuggers. What's cool is that the code is also optimized during this build operation. And, all calls to Debug class methods in your code are disabled while calls to Trace class methods are left.
Of course, when you compile in Debug mode, the application can be debugged at the source level and you have all the power of Visual Studio .NET and other source-level debug tools at your disposal. Obviously, code compiled in Debug mode does not perform quite as well as Release-mode code does.

Wednesday, June 16, 2010

Passing value from popup window to parent form's TextBox

Passing values from a popup window back to the parent page is an often asked question. Especially when there is a GridView type control in the popup. In the following example we will be using two forms. The parent form will be parent.aspx and the popup will be popup.aspx. Also note that the parent.aspx form is derived from some MasterPage. Code is provided both in VB.Net and C#.Net.
--- .aspx of parent form ---
<script type="text/javascript">
function OpenPopup() {
    window.open("popup.aspx","List","scrollbars=no,resizable=no,width=400,height=280");
    return false;
}
</script>
      
<asp:TextBox ID="txtPopupValue" runat="server" Width="327px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Show List" />
--- .cs of parent.aspx if C#.net is the language ---
if (!IsPostBack) {
    this.Button1.Attributes.Add("onclick", "javascript:return OpenPopup()");
}
--- .aspx of popup form ---
<script language="javascript">
function GetRowValue(val)
{
    // hardcoded value used to minimize the code.
    // ControlID can instead be passed as query string to the popup window
    window.opener.document.getElementById("ctl00_ContentPlaceHolder1_TextBox2").value = val;
    window.close();
}
</script>

<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1">
    <Columns>
        <asp:TemplateField>
            <AlternatingItemTemplate>
                <asp:Button ID="btnSelect" runat="server" Text="Select" />
            </AlternatingItemTemplate>
            <ItemTemplate>
                <asp:Button ID="btnSelect" runat="server" Text="Select" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>
--- .cs file if C#.net is the language ---
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e) {
    if ((e.Row.RowType == DataControlRowType.DataRow)) {
        //assuming that the required value column is the second column in gridview
        ((Button)e.Row.FindControl("btnSelect")).Attributes.Add("onclick", "javascript:GetRowValue('" + e.Row.Cells[1].Text + "')");
    }
}

Saturday, June 12, 2010

SQL Play

Find duplicate rows in a table
SELECT sid, mark, COUNT(*) AS Counter
FROM marks
GROUP BY sid, mark
HAVING (COUNT(*) > 1)

How to delete the rows which are duplicate (don’t delete both duplicate records).
SET ROWCOUNT 1
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
WHILE @@rowcount > 0
DELETE yourtable
FROM yourtable a
WHERE (SELECT COUNT(*) FROM yourtable b WHERE b.name1 = a.name1 AND b.age1 = a.age1) > 1
SET ROWCOUNT 0

How to find 6th highest salary
SELECT TOP 1 salary
FROM (SELECT DISTINCT TOP 6 salary
FROM employee
ORDER BY salary DESC) a
ORDER BY salary

Tuesday, June 8, 2010

How to get a File Upload control work with an UpdatePanel

The FileUpload control does not work with asynchronous post backs and therefore does not work from within an AJAX UpdatePanel.
The trick to make the FileUpload to work within an Ajax UpdatePanel is to setup a PostBackTrigger in the UpdatePanel control.

This issue I faced in my one of application ipromotedigital


<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<Triggers >
<asp:PostBackTrigger ControlID ="Button1" />
</Triggers>
<ContentTemplate >
<asp:FileUpload ID ="fileupload1" runat ="server" /><br />     
<asp:Button ID ="Button1" runat ="server" Text ="Upload" OnClick="Button1_Click" /><br />
<asp:Label ID ="Lable1" runat ="server"  Text =""></asp:Label>
<asp:LinkButton ID ="LinkButton1" runat="server" Text ="Click Here" OnClick="LinkButton1_Click"></asp:LinkButton>
</ContentTemplate>
</asp:UpdatePanel>

Why upload fails when using an ASP.NET FileUpload control to upload large files

For security reasons, ASP.NET is limited in terms of an uploaded file size. The default maximum file size is 4 MB but this can be changed by modifying the MaxRequestLength attribute of Machine.config's <httpRuntime> element.


This issue I faced in my one of application ipromotedigital

<httpRuntime executionTimeout="240" maxRequestLength="20480" />

How to clear the session when the user closes a window

<script type="text/javascript">
function window.onbeforeunload()
{
    var xmlHttp;
    try
    {
        // Firefox, Opera 8.0+, Safari
        xmlHttp=new XMLHttpRequest();
    }
    catch (e)
    {
        // Internet Explorer
    try
    {
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e)
    {
        try
        {
            xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch (e)
        {
            alert("Your browser does not support AJAX!");
            return false;
        }
    }
    if(event.clientX>document.body.clientWidth&&event.clientY<0||event.altKey)
    {
        xmlhttp.open("GET","exit.aspx",false);
        xmlhttp.send();
    }
 }
</script>

How to register the JavaScript function at Code-Behind

Use ResterStartupScript
this.Page.ClientScript.RegisterStartupScript(this.GetType(),"alert","<script>alert(‘hello’);</script>");
Use Literal control,
private void Button2_Click(object sender, System.EventArgs e)
{
    string str;
    str="<script language='JavaScript'>";
    str+="selectRange()";
    str+="<script>";
    Literal1.Text=str;
}

How to access a control by using JavaScript

Reference the ClientID property (or UniqueID) of the control in the JavaScript.
protected void Page_Load(object sender, EventArgs e)
{
    Button btn= new Button();
    btn.ID = "btn5";
    btn.Attributes.Add("runat", "server");
    btn.Attributes.Add("onclick", "pop('" + btn.ClientID + "')");
    btn.Text = "Test";
    this.form1.Controls.Add(btn);
}

function pop(InputBoxID)
{
    var InputControl = document.getElementById(InputBoxID);
    alert(InputControl.value);
}

Or you can use the following method:

 
btn.Attributes.Add("onclick", "pop(this)");
function pop(InputBox)
{
    alert(InputBox.value);
}

Unable to access Session in HttpHandler

It you are unable to access Session in HttpHandler and getting error “Object reference not set to an instance of an object”, so to fix this issue implement “IRequiresSessionState” interface like below after implimenting IRequiresSessionState you will be able to access Sessions in HttpHandler


public class CallBackHandler : IHttpHandler, IRequiresSessionState

Monday, June 7, 2010

Callback and Manual Partial Page Rendering

As Callback doesn’t cause postback and page rendering neither full nor even partial. We can communicate with server (IIS) and our server side code runs there successfully and could rebind our controls like Dropdownlist, Gridview, Listview, Datalist, Repeater or any server side control to which you assign data but problem is when page wont render, its controls wont render and if controls wont render then changes wont reflect and when changes wont reflect there wont be anything at front end to show on webpage.
Article is mainly about Callback and Rendering Controls but through this tutorial you can also learn many other things like brief introduction of Postback, Rendering, Create server side controls dynamically, Create Datatable dynamically in memory to bind with create server side controls means binding, get server side control at client side and set their properties and registering client side event of server side control from/through server side code.
First of all, I would like to brief some terms which I believe every web developer should aware of.

Postback
Postback is a mechanism of communication between client-side (browser) and server-side (IIS). Through postback all contents of page/form(s) sent to the server from client for processing and after following page life cycle all server side contents get render into client side code and client (browser) display that contents. Callback is another way of communication between server and client. Callback doesn’t follow the page life cycle which followed by in standard postback and doesn’t even cause Rendering.

Rendering
Rendering is process of converting server side code/contents into client side code/content so client (browser) can understand that code and could display the output. Browser can understand or you may say decode code of client side languages and scripts like HTML, DHTML, XHTML, Javascript, Vbscript and a long list.
If rendering wont happen then changes won’t reflect which happens on server at client side. Ajax leverages partial postback automatically whereas callback doesn’t cause, so programmer needs to perform that task manually.
ASP.NET team has created RenderControl method with its each control so by using that control we can render our control very easily.

CALLBACK
CALLBACK is lightweight process, It uses well known xmlhttp object internally to call server side method, it doesn’t cause page postback so doesn’t cause page rendering so we to show output at client side we need to make output html ourselves and render controls manually.

ICALLBACKEVENTHANDLER
ICALLBACK implemented in asp.net by using ICALLBACKEVENTHANDLER interface has two methods, one of them used to be call from javascript (client side code) and other one return result asynchronously back to javascript function.
We just need to perform some action through server side code at server side and needs to return results but results could are in instance or object of any class which could be not easy for javascript code to handle easily so here we prefer JSON which stands for Javascript Object Notation.

Real Time Scenario with implementation
Suppose we have categories, subcategories, products data and needs to populate categories and subcategories which depend upon categories data would be populate in two different dropdownlists. For products data which is multicolumn and we need to show that data in tabular format so I would prefer Gridview control.
So the situation would be load/populate categories on Page_Load and load/populate subcategories on the basis of selected category using callback and finally load products into Gridview on the basis of selected subcategory.
Before starting coding, I would like to write Pseudo code for better understanding.

Pseudo Code
  1. Create Server side controls e.g. Dropdownlists and Gridview
  2. Load Categories on Page load
  3. Implement ICallbackEventHandler interface
  4. Create subcategories data in server memory to bind to Subcategory dropdownlist.
  5. Render control (subcategory dropdownlist) and show output.
  6. Create products data in server memory to bind to Products gridview.
  7. Render Control (products gridview) and return rendered contents to client side to show
  8. Set innerHTML of each control by rendered contents
Download Code from here

http://sites.google.com/site/akshatsharma80/home/asp-net/callback-and-manual-partial-page-rendering?pli=1

Thursday, June 3, 2010

How to get previous page name in c#?

1) Session Variable Previous page/Viewstate Variable
2) QueryString http://yoursite.com/thispage?from=PreviousPage
3) Using Property of a class e.g. By setting Property set while redirecting and get in target page.
4) By following methods
public string GetCurrentPageName()
{
 string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
 System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
 string sRet = oInfo.Name;
 return sRet;
}

public string GetPreviousPageName()
{
 string sPath = Page.PreviousPage.Request.Url.AbsolutePath;
 System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath);
 string sRet = oInfo.Name;
 return sRet;
}

protected void Page_Load(object sender, EventArgs e)
{
 if (Request.UrlReferrer != null)
 {
   //geting the name of the previous page in a variable sPrevPage  
   string sPrevPage = Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];
   Response.Write("Previous page is - " + sPrevPage);
 }

Populating the DropDownList with Enum

Suppose you want to populate a DropDownList with Enum. Using System.Reflection it can be done as below

<asp:DropDownList ID="ddlPackageType" runat="server" Width="60">
</asp:DropDownList>

public struct PackageTypes
{
   public const string Document = "01";
   public const string Package = "02";
}

private void FilPackageType()
{
  FieldInfo[] myEnumFields = typeof(PackageTypes).GetFields();
  foreach (FieldInfo myField in myEnumFields)
  {
   if(!myField.IsSpecialName && myField.Name.ToLower() != "notset")
   {
     string myValue = (string)myField.GetValue(0);
     ddlPackageType.Items.Add(new ListItem(myField.Name, myValue.ToString()));
   }
  }
}

Download Article