Thursday, December 10, 2009

Introduction to JSTL

1. What is JSTL?

JSTL stands for JSP
Standard Tag Library. JSTL has been standardized and is being one of the most
important technologies in implementing J2EE Web Application. The main objective
of the JSTL is basically to simplify the Java codes within JSP (scriptlets) as
well as to increase the level of reusability within our J2EE web application. Before
JSTL is introduced, J2EE Web Applications (especially in the presentation layer
– JSP) are extremely complex and are very tough to be maintained. It is true
that the new developer may take some time to understand all the underlying
codes within J2EE Web Application This is where JSTL should help.


Here is a simple JSTL flow concept; JSTL is
compiled into a servlets (Java codes) before being displayed to JSP. Some
classes of standard.jar are required to parse and translate these JSTL tags
into servlets (Java codes). Lastly but not least, the servlet that has been
compiled will be executed accordingly.


There are many more advantages
of using JSTL compared to scriptlets. Therefore, it is recommended to replace
scriptlets with JSTL in the presentation layer (JSP).


There
are 5 major types of JSTL tags:

  1. JSTL Core tags,
    prefixed with c
  2. JSTL Format tags,
    prefixed with fmt
  3. JSTL Function
    tags, prefixed with fn
  4. JSTL Database
    tags, prefixed with sql
  5. JSTL XML tags,
    prefixed with x


JSTL Core Tags
<%@ taglib
uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Mainly used for replacement of scriptlet logical
tags as well as basic URL handling tag such as catch, choose, if, forEach,
param, when, redirect, import, url, etc.



JSTL Format Tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"
prefix="fmt" %>

Mainly used for displaying number and date time format. This could be
used for internationalization support as well. Tags examples are setLocale,
setTimeZone, setBundle, formatNumber, formatDate, etc.



JSTL Function Tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions"
prefix="fn" %>

Very useful JSTL tags. Most are used in
conjunction with JSTL core tags. These tags are designed for manipulating
string.



JSTL Database Tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql"
prefix="sql" %>

Tags are used to interact with database level. With database tags you
could do transaction, update and query the database from your UI level.
Personally, I do not prefer these tags. The MVC design pattern should always be
retained.



JSTL XML tags
<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x"
%>

Similar to core tags, except xml tags will
deal with xml stuffs like parsing xml documents, validating xml documents, output
an xpath and etc.


For depth details to all JSTL tags, you can
find more information within
your NetBean’s installation folder i.e. installation_netbeans_folder\enterprise1\docs\

Additionally, JSTL accepts the conditional operators
like ‘eq’, ‘ne’, ’==’, ’null’, ’empty’, ’not’, ’!=’, ’>=’, ’<=’, ’and’, ’&&’,
’or’, ’||’ all are valid.


Here is the mapping of relational and
logical operators with JSP Notations.


Operators

JSP
Notation


>

gt

<

Lt

>=

ge

<=

le

==

eq

!=

ne

&&

and

||

or

!

not

‘’

empty

/

div

%

mod
While other arithmetic operators such as +,
-, and * can also be used together with the JSTL tag as well.



Join my groups to share knowledge at
http://groups.google.com/group/rjetla?hl=en
http://rjetla.blogspot.com/

Thanks & Regards

l¯¯l¯)
l__l\__\aju
.     l¯¯l
(¯¯(/__/etla

"falling down is not a crime, staying down is a crime"





Monday, December 7, 2009

Beans and Form processing


Forms are a very common method of interactions in web sites.  JSP makes forms processing specially easy.
The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean.  You just need to define a class that has a field corresponding to each field in the form.  The class fields must have "setters" that match the names of the form fields.  For instance, let us modify our GetName.html to also collect email
address and age.

The new version of GetName.html is

<HTML>
<BODY>
<FORM METHOD=POST ACTION="SaveName.jsp">
What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR>
What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR>
What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4>
<P><INPUT TYPE=SUBMIT>
</FORM>
</BODY>
</HTML>

To collect this data, we define a Java class with fields "username", "email" and "age" and we provide setter methods "setUsername", "setEmail" and "setAge", as shown.  A "setter" method is just a method that starts with "set" followed by the name of the field.  The first character of the field name is upper-cased.
So if the field is "email", its "setter" method will be "setEmail".  Getter methods are defined similarly, with "get" instead of "set".   Note that the setters  (and getters) must be public.

package user;
public class UserData {

    String username;
    String email;
    int age;
 
    public void setUsername( String value )
    {
        username = value;
    }
 
    public void setEmail( String value )
    {
        email = value;
    }
 
    public void setAge( int value )
    {
        age = value;
    }
 
    public String getUsername() { return username; }
 
    public String getEmail() { return email; }
 
    public int getAge() { return age; }

}

The method names must be exactly as shown.  Once you have defined the class, compile it and make sure it is available in the web-server's classpath.  The server may also define special folders where you can
place bean classes, e.g. with Blazix you can place them in the "classes" folder.  If you have to change the classpath, the web-server would need to be stopped and restarted if it is already running.  Note that we are using the package name user, therefore the file UserData.class must be placed in a folder named
user under the classpath entry. Now let us change "SaveName.jsp" to use a bean to collect the
data.

<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>
<HTML>
<BODY>
<A HREF="NextPage.jsp">Continue</A>
</BODY>
</HTML>

All we need to do now is to add the jsp:useBean tag and the jsp:setProperty tag!  The useBean tag will look for an instance of the "user.UserData" in the session.  If the instance is already there, it will update the old instance.  Otherwise, it will create a new instance of user.UserData (the instance of the user.UserData is called a bean), and put it in the session. The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean!

Let us modify NextPage.jsp to retrieve the data from bean..
<jsp:useBean id="user" class="user.UserData" scope="session"/> 
<HTML>
<BODY>
You entered<BR>
Name: <%= user.getUsername() %><BR>
Email: <%= user.getEmail() %><BR>
Age: <%= user.getAge() %><BR>
</BODY>
</HTML>

Notice that the same useBean tag is repeated.  The bean is available as the variable named "user" of class "user.UserData". The data entered by the user is all collected in the bean. We do not actually need the "SaveName.jsp", the target of GetName.html could have been NextPage.jsp, and the data would still be available the same way as long as we added a jsp:setProperty tag. But in the next tutorial, we will actually use SaveName.jsp as an error handler that automatically forwards the request to NextPage.jsp,
or asks the user to correct the erroneous data.

Exercise:  1)  Write a JSP/HTML set that allows a user to enter the name of a system property, and then displays the value returned by System.getProperty for that property name (handle errors appripriately.)
2)  Go back to the exercises where you manually modified boolean variables. Instead of a boolean variable, make these come from a HIDDEN form field that can be set to true or false.

Join my groups to share knowledge at
http://groups.google.com/group/rjetla?hl=en
http://rjetla.blogspot.com


Thanks & Regards


l¯¯l)¯¯)
l__l\__\aju
       l¯¯l
(¯¯(/__/etla

Tuesday, November 17, 2009

Configuring outlook for accessing Gmail

To configure Outlook 2007 for your Gmail address:

  1. Enable POP in your email account. Don't forget to click Save Changes when you're done.
  2. Open Outlook.
  3. Click the Tools menu, and select Account Settings...
  4. On the E-mail tab, click New...
  5. If you are prompted to Choose E-mail Service, select Microsoft Exchange, POP3, IMAP, or HTTP, and click Next.
  6. Fill in all necessary fields to include the following information:

    Your Name: Enter your name as you would like it to appear in the From: field of outgoing messages.
    Email Address: Enter your full Gmail email address (username@gmail.com). Google Apps users, enter your full address in the format username@your_domain.com.
    Password: Enter your email password.

    Manually configure server settings or additional server types: Leave this option unchecked if you want to automatically configure Outlook 2007. If you want to manually configure Outlook 2007, check this box now. Google Apps users should configure manually as follows.


  7. Click Next. If you are configuring Outlook 2007 automatically, you're done! Just click Finish.


  8. If you are configuring Outlook 2007 manually, select Internet E-mail and click Next.
  9. Verify your User Information, and enter the following additional information:

    Server Information

    Account Type: POP3

    Incoming mail server:
    pop.gmail.com (Google Apps users, enter the server names provided, don't add your domain name in these steps)

    Outgoing mail server (SMTP):
    smtp.gmail.com

    Logon Information

    User Name: Enter your Gmail username (including @gmail.com). Google Apps users, enter your full address in the format username@your_domain.com

    Password: Enter your email password.

    Require logon using Secure Password Authentication (SPA): Leave this option unchecked.


  10. Click the More Settings... button, and select the Outgoing Server tab.
  11. Check the box next to My outgoing server (SMTP) requires authentication and select Use same settings as my incoming mail server.


  12. Click the Advanced tab, and check the box next to This server requires an encrypted connection (SSL) under Incoming Server (POP3).
  13. In the Outgoing server (SMTP) box, enter 587, and select TLS from the drop-down menu next to Use the following type of encrypted connection:.


  14. Click OK.
  15. Click Test Account Settings... After receiving 'Congratulations! All tests completed successfully', click Close.
  16. Click Next, and then click Finish.

Congratulations! You're done configuring your client to send and retrieve Gmail messages.

Friday, November 13, 2009

Use Gmail IMAP in Microsoft Outlook 2007

We’ve all been hearing about the new IMAP support in Gmail, but how do we access that from Outlook? Those of you that have been waiting patiently will be happy to know all the instructions are on this page.
Using IMAP we can synchronize email across multiple devices, since the mail stays on the server. You already stopped reading this part and skipped down to the instructions, didn’t you?
Enable IMAP in Gmail Settings
Open your Settings panel in Gmail, and then click on the “Forwarding and POP/IMAP” tab.
image
Now click the Enable IMAP radio button, and click Save Changes.
image
Add Account to Outlook
Use the Tools menu you to open the Account Settings panel.
image
If this is your first account you’ll be prompted for the wizard, otherwise you’ll need to click the New button under the E-mail tab.
image
Now select the “Microsoft Exchange, POP3, IMAP or HTTP” option and hit next.
image
Select the checkbox for “Manually configure server settings” and everything on that page will gray out. Hit the next button again.
image
Now select “Internet E-mail”  (Didn’t we just do this? This wizard is taking too long…)
image
Finally we can enter some settings! Add in all your personal information here.
image
Note: If you are outside of the US you may need to use imap.googlemail.com and smtp.googlemail.com instead of imap.gmail.com and smtp.gmail.com.
Note: for Gmail Apps accounts, you’ll need to put in your full email address wherever you see an @gmail.com above. For instance, if your account was geek@howtogeek.com you would put that in the E-mail address field as well as the User Name field.
Click on the “More Settings” button and find the Outgoing Server tab, where you’ll need to check the box for “My outgoing server requires authentication”
image
Now choose the Advanced tab, and enter the following values (Very important)

  • Incoming Server: 993
  • Incoming Server encrypted connection: SSL
  • Outgoing Server: 587
  • Outgoing Server encrypted connection: TLS
image
Note: If you are having an issue with your sent email not showing up in Gmail, you can use the Folders tab, and then select the [Gmail] \ Sent Mail folder.
Note: Only do this step if your mail is not showing up, otherwise it will duplicate the sent mail.
image
Now that you’ve closed out that dialog, you can click the Test Account Settings button to make sure everything is going to work.
image
If all goes well, you should see a success message.
image
Note: Some ISPs restrict outgoing mail, so if you have a problem sending a test message you’ll need to consult with their documentation.
Accessing Your Mail
Now that everything is working you’ll notice a new set of folders for your Gmail account. (I’m using Gmail apps, which is why you don’t see an @gmail.com email address)
All of your labels will show up as separate folders, and the built-in “folders” in Gmail will be under the new [Gmail] folder.
 image
Outlook Flags = Gmail Stars
If you want to star a message in Gmail, you just need to flag it in Outlook. When I flagged this message from Mysticgeek…
image 
It shows up in Gmail as a starred message. (And it works the other way too)
image
Sending Email from Outlook
To send a new email from your Gmail account, just change the “Account” drop-down to your Gmail address before you send a message.
image
Note that if you only use Gmail, you won’t have this drop-down and it will default to your Gmail.
Final Thoughts
Here’s a few things to keep in mind:

  • Gmail Labels = Outlook Folders. To label a message, add it to a folder.
  • Gmail Stars = Outlook Flags.
  • Do Not move spam messages to the “Junk E-mail” folder in Outlook, move them to the [Gmail] \ Spam folder.
  • Outlook has a built-in Search Folder for “Large Mail”, which will let you easily find messages with large attachments.
Now that you can access your starred and labeled messages, you can start using Outlook’s excellent Search Folders to find messages more easily.



Raju Jetla

Tuesday, November 3, 2009

How To Map Output Parameter From Stored Procedure To LINQ


 In this article we will create one more SP but this will be returning one output parameter. We will map this SP to LIQ file and consume it using LIQ. So let’s crate one stored procedure which will take two parameters as input which is username and password of the user and if the user credentials matches, we will return one output parameter.


This output parameter will tell us weather user is authenticated or not. If he is authenticated we will redirect our users to links pages where he can see all the links that he has stored in his Favorite list. First of all let’s crate stored procedure in our database.  




SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

ALTER PROCEDURE fm_AuthenticateUser

     

      @Username varchar(150),

      @Password varchar(16), 

      @Uid int OUTPUT

AS

BEGIN

     

      SET NOCOUNT ON;  

      Declare @Pass varchar(16)

      Declare @id int

      SELECT @Pass = Password, @id = UserId

      FROM dbo.lnkUsers

      WHERE Username = @Username

     

      IF @Password <> @Pass

      BEGIN

            SET @Uid = 0

      END

      ELSE

      BEGIN

            SET @Uid = @id

      END

END

GO
As you see if the user credentials are not matching we will set the output parameter to zero. If they are matches we will return the user id of that user. On the basis of this return parameter we will redirect our user to appropriate page.


Once this is done go to your and map this stored procedure to your .net application similar way we did before. If you have not read previous articles please read them here.  As I mentioned this is a special case where the stored procedure is returning us some parameter which we need to handle in LIQ. Before we go ahead and handle that let’s first create a login page where user can enter his/her credentials. For now I will just add this stuff to my default page as that will be the start page of our application. Make your page look like as below.


Now let’s add this code into the click event of your login button.


protected void btnLogin_Click(object sender, EventArgs e)

    {

        LinkManagerDataContext lm = new LinkManagerDataContext();

        Nullable<int> userid = null;

        lm.fm_AuthenticateUser(txtUsername.Text.ToString(), txtPassword.Text.ToString(),ref userid);

        if (userid != 0)

        {

            Session["uid"] = userid;

            Response.Redirect("links.aspx");

        }

        else

        {

            lblREsult.Text = "Authentication Failed";

        }

    }
If you see here we defined our userid integer is because LIQ to SQL maps output parameters from SP as reference type (using ref keyword)



Once the user is authenticated we will store his userid into session and foreword him to the links page where we will retrieve the user’s favorite links using the userid we have in session.


For this write code below in the page load event of the links page.


protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

            if (Session["uid"] != null)

            {

                LinkManagerDataContext lm = new LinkManagerDataContext();

                var links = lm.fm_GetLinks(Convert.ToInt32(Session["uid"]));

                grdLinks.DataSource = links;

                grdLinks.DataBind();

            }

        }




    }




Go ahead and run the application. Once the credentials are matched you should see some thing like below.



NOTE:

 I have written a separate article on how to retrieve data using stored procedure accepting an input parameter before this one so the links page might have some extra controls and its code behind may have some extra code as well.

Watch the gray out area on the above screen shot.



So in this article we understood how we can handle the stored procedure’s output parameters using LIQ to SQL functionality in your application.


Thanks

Raju Jetla

Monday, October 19, 2009

Introduction to LINQ Queries


Language-Integrated Query (LINQ)
reference:MSDN


A query is an expression that retrieves data from a data source. Queries are usually expressed in a specialized query language. Different languages have been developed over time for the various types of data sources, for example SQL for relational databases and XQuery for XML. Therefore, developers have had to learn a new query language for each type of data source or data format that they must support. LINQ simplifies this situation by offering a consistent model for working with data across various kinds of data sources and formats. In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, .NET collections, and any other format for which a LINQ provider is available.


Three Parts of a Query Operation
 
All LINQ query operations consist of three distinct actions:

  1. Obtain the data source.
  2. Create the query.
  3. Execute the query.
The following example shows how the three parts of a query operation are expressed in source code. The example uses an integer array as a data source for convenience; however, the same concepts apply to other data sources also. This example is referred to throughout the rest of this topic.



C#
class IntroToLINQ
{        
    static void Main()
    {
        // The Three Parts of a LINQ Query:
        //  1. Data source.
        int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

        // 2. Query creation.
        // numQuery is an IEnumerable
        var numQuery =
            from num in numbers
            where (num % 2) == 0
            select num;

        // 3. Query execution.
        foreach (int num in numQuery)
        {
            Console.Write("{0,1} ", num);
        }
    }
}
 
The following illustration shows the complete query operation. In LINQ the execution of the query is distinct from the query itself; in other words you have not retrieved any data just by creating a query variable.

Complete LINQ Query Operation


 The Data Source 
In the previous example, because the data source is an array, it implicitly supports the generic IEnumerable<(Of <(T>)>)  interface. This fact means it can be queried with LINQ. A query is executed in a foreach statement, and foreach requires IEnumerable
or IEnumerable<(Of <(T>)>) or a derived interface such as the generic IQueryable<(Of <(T>)>) are called queryable types. A queryable type requires no modification or special treatment to serve as a LINQ data source. If the source data is not already in memory as a queryable type, the LINQ provider must represent it as such. For example, LINQ to XML loads an XML document into a queryable XElement type:



C#
// Create a data source from an XML document.
// using System.Xml.Linq;
XElement contacts = XElement.Load(@"c:\myContactList.xml");

With LINQ to SQL, you first create an object-relational mapping at design time either manually or by using the Object Relational Designer (O/R Designer) . You write your queries against the objects, and at run-time LINQ to SQL handles the communication with the database. In the following example, the Northwnd class encapsulates the database, and Customers represents a specific table in the database. The query, when executed, will return a sequence of Customer objects, whose type is inferred by the compiler. The type of the query result, IQueryable<(Of <(T>)>) , compiles to an expression tree, which is converted at run time into a SQL query.


Visual Basic
Dim db As New Northwnd("c:\northwnd.mdf")

' Query for customers in London.
Dim custQuery = _
    From cust In db.Customers _
    Where cust.City = "London" _
    Select cust

C#
Northwnd db = new Northwnd(@"c:\northwnd.mdf");

// Query for customers in London.
IQueryable custQuery =
    from cust in db.Customers
    where cust.City == "London"
    select cust;
For more information about how to create specific types of data sources, see the documentation for the various LINQ providers. However, the basic rule is very simple: a LINQ data source is any object that supports the generic IEnumerable<(Of <(T>)>)  interface, or an interface that inherits from it.

The query specifies what information to retrieve from the data source or sources. Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. A query is stored in a query variable and initialized with a query expression. To make it easier to write queries, C# has introduced new query syntax.
The query in the previous example returns all the even numbers from the integer array. The query expression contains three clauses: from, where and select. (If you are familiar with SQL, you will have noticed that the ordering of the clauses is reversed from the order in SQL.) The from clause specifies the data source, the where clause applies the filter, and the select clause specifies the type of the returned elements. These and the other query clauses are discussed in detail in the LINQ Query Expressions (C# Programming Guide) section. For now, the important point is that in LINQ, the query variable itself takes no action and returns no data. It just stores the information that is required to produce the results when the query is executed at some later point. For more information about how queries are constructed behind the scenes, see Standard Query Operators Overview [ http://msdn.microsoft.com/en-us/library/bb397896.aspx ] .
Queries can also be expressed by using method syntax. For more information, see LINQ Query Syntax versus Method Syntax (C#)

Deferred Execution

As stated previously, the query variable itself only stores the query commands. The actual execution of the query is deferred until you iterate over the query variable in a foreach statement. This concept is referred to as deferred execution and is demonstrated in the following example:

C#
//  Query execution. 
foreach (int num in numQuery)
{
    Console.Write("{0,1} ", num);
}
The foreach statement is also where the query results are retrieved. For example, in the previous query, the iteration variable num holds each value (one at a time) in the returned sequence.
Because the query variable itself never holds the query results, you can execute it as often as you like. For example, you may have a database that is being updated continually by a separate application. In your application, you could create one query that retrieves the latest data, and you could execute it repeatedly at some interval to retrieve different results every time.

Forcing Immediate Execution

Queries that perform aggregation functions over a range of source elements must first iterate over those elements. Examples of such queries are Count, Max, Average, and First. These execute without an explicit foreach statement because the query itself must use foreach in order to return a result. Note also that these types of queries return a single value, not an IEnumerable collection. The following query returns a count of the even numbers in the source array:

C#
var evenNumQuery = 
    from num in numbers
    where (num % 2) == 0
    select num;

int evenNumCount = evenNumQuery.Count();
To force immediate execution of any query and cache its results, you can call the ToList<(Of <(TSource>)>) or ToArray<(Of <(TSource>)>)  methods.

C#
List<int> numQuery2 =
    (from num in numbers
     where (num % 2) == 0
     select num).ToList();

// or like this:
// numQuery3 is still an int[]

var numQuery3 =
    (from num in numbers
     where (num % 2) == 0
     select num).ToArray();
You can also force execution by putting the foreach loop immediately after the query expression. However, by calling ToList or ToArray you also cache all the data in a single collection object.
 

note: all the content is taken from MSDN

I love to hear feedback, please do write it


Thanks
Raju Jetla


Friday, October 2, 2009

What is Open ID?

OpenID is an open, decentralized standard for authenticating users which can be used for access control, allowing users to log on to different services with the same digital identity where these services trust the authentication body.

OpenID replaces the common login process that uses a login-name and a password, by allowing a user to log in once and gain access to the resources of multiple software systems.

The term OpenID can also refer to an ID used in the standard.
An OpenID is in the form of a unique URL, and is authenticated by the user's 'OpenID provider' (that is, the entity hosting their OpenID URL). The OpenID protocol does not rely on a central authority to authenticate a user's identity. Since neither the OpenID protocol nor Web sites requiring identification may mandate a specific type of authentication, non-standard forms of authentication can be used, such as smart cards, biometrics, or ordinary passwords.

OpenID authentication is now used and provided by several large websites. Providers include AOL, BBC, Google,IBM, Microsoft, MySpace, Orange, PayPal, VeriSign, Yandex, Ustream and Yahoo!.


Thanks & Regards

Raju Jetla
"falling down is not a crime, staying down is a crime"

Saturday, September 19, 2009

Email client mail server configuration

http://www.emailaddressmanager.com/tips/mail-settings.html

Join my groups to share knowledge at
http://groups.google.com/group/rjetla?hl=en
Thanks & Regards

Raju Jetla
"falling down is not a crime, staying down is a crime"

Sent from Microsoft Windows Mobile®

Friday, August 21, 2009

How to correctly highlight GridView rows on Mouse Hover in ASP.NET

GridView Component had brought some really nice features to the ASP.Net development. And even those features that it lacks can be easily added via customization or inheritance.

One of the things that GridView lacks are all those client-side bells and whistles that make todays web users happy (or miserable, depending on how developers over-use them http://www.aspdotnetfaq.com/fckeditor/editor/images/smiley/msn/wink_smile.gif).

For example, very often it is required to highlight the data rows when mouse pointer is over the row (Mouse Hover effect).

This is not something that GridView does by default, but as i said, it is very easy to add new features to the GridView.
We can add few lines of JavaScript and thats it.

But to create this effect in a way as it should be done, a little planning is necessary:

If you ask the almighty Google, it will direct you to the various implementations of this effect for GridView but most of them do not take into account GridView's ItemStyle and AlternatingItemStyle properties and just override them when changing row colors.

What we are going to do is to implement mouse hover row highlighting with respect of all GridView properties, and restoring their original values when the mouse pointer is moved away from the rows/GridView.

In order to highlight the row on mouse hover, we need to add some custom JavaScript code to onmouseover and onmouseout event handlers of the rows of our GridView.

We can do this by placing this code to the RowCreated event handler of our GridView:


protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)

{

// only apply changes if its DataRow

if (e.Row.RowType == DataControlRowType.DataRow)

{

// when mouse is over the row, save original color to new attribute, and change it to highlight yellow color

e.Row.Attributes.Add("onmouseover",

"this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='#EEFF00'");

// when mouse leaves the row, change the bg color to its original value

e.Row.Attributes.Add("onmouseout",

"this.style.backgroundColor=this.originalstyle;");

}

}


What this code actually does?

RowCreated event is fired immediately after each row is created in our GridView. So for each created row, we first check if its a DataRow (not Header of Footer for example) and if it is, we add the JavaScript code via Add method of the Attributes collection (AttributeCollection type) that has name-value pairs of the rendering attributes of the GridViewRow.

In onmouseover handler code, we first store (for later restoring) the original background color of the row in a custom attribute we called "originalstyle" and we then change it to a custom color (light Yellow in this case).

In onmouseout handler, we restore the original background color of the row from the "originalstyle" attribute.

And that is it. If you bind this GridView with some data and display it on a page, when you move your mouse pointer over any of the rows, it will change its background color into Yellow. And when you move mouse out of the row, the original background color of the row is restored.

IMPORTANT: This works correctly even if you have set the AlternatingRowStyle of the GridView and even if the row was previously selected (this detail is something that is missing in all other implementations of this GridView behavior we have seen on the internet).

Ok, now that we solved this, why not make a custom WebControl out of it by inheriting the original ASP.NET GridView control and adding highlighting feature to it?

Its really simple, here is the code of the HoverGridView custom WebControl:


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.Drawing;

/// <summary>

/// Summary description for HoverGridView

/// </summary>

namespace Roboblob.WebControls

{

[ToolboxData("<{0}:HoverGridView runat=server></{0}:HoverGridView>")]

public class HoverGridView : System.Web.UI.WebControls.GridView

{

public bool MouseHoverRowHighlightEnabled

{

get

{

if (ViewState["MouseHoverRowHighlightEnabled"] != null)

return (bool)ViewState["MouseHoverRowHighlightEnabled"];

else

return false;

}

set { ViewState["MouseHoverRowHighlightEnabled"] = value; }

}

public Color RowHighlightColor

{

get

{

if (ViewState["RowHighlightColor"] != null)

return (Color)ViewState["RowHighlightColor"];

else

{

// default color

return Color.Yellow;

}

}

set { ViewState["RowHighlightColor"] = value; }

}

protected override void OnRowCreated(GridViewRowEventArgs e)

{

base.OnRowCreated(e);

if (MouseHoverRowHighlightEnabled)

{

// only apply changes if its DataRow

if (e.Row.RowType == DataControlRowType.DataRow)

{

// when mouse is over the row, save original color to new attribute

// and change it to highlight yellow color

e.Row.Attributes.Add("onmouseover",

string.Format("this.originalstyle=this.style.backgroundColor;this.style.backgroundColor='{0}'",

ColorTranslator.ToHtml(RowHighlightColor)));

// when mouse leaves the row, change the bg color to its original value

e.Row.Attributes.Add("onmouseout",

"this.style.backgroundColor=this.originalstyle;");

}

}

}

}

}

And here is how to use this custom WebControl on a WebForm:

First we must register it on the top of our aspx page:

<%@ Register Namespace="Roboblob.WebControls" TagPrefix="roboblob" %>


And when we place our custom GridView on the form here is how its declaration looks like:

<roboblob:HoverGridView runat="server" MouseHoverRowHighlightEnabled="True" RowHighlightColor="Green" ID="HoverGridView1" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1">

<Columns>

<asp:CommandField ShowSelectButton="True" />

<asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"

SortExpression="id" />

<asp:BoundField DataField="name" HeaderText="name" SortExpression="name" />

</Columns>

</roboblob:HoverGridView>


As you can see its really only a few lines of code, and yet we have created a custom WebControl that we can place on any WebForm, switch the highlighting on/off, change the highlight color etc.

This is the beauty of creating and using WebControls and Controls in general...

We could add many other features to our custom GridView, like different colors for alternating rows, for selected rows etc but i will leave that as something for you to play with.

Raju Jetla

Recent Comments