Friday, September 23, 2011

JQuery - Image Slide Show using JQuery

In this article i will show you how to create dynamic Image slide show using JQuery and Web Service.

Step 1
Download JQuery Script from the following Link
JQuery 1.6.4

Step 2
Create a Web Application and give the solution name as SolSimpleSlideShowJQuery.


Step 3
Save images in Folder,Create a New Folder in the Solution and give folder name as Images,it is look like this


Click on Image for better View


Step 4
Add XML file in the App_Data folder and give the file name as ImageData.xml,it is look like this


Click on Image for better View


Step 5
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called ImagePath,it's look like this
<?xml version="1.0" encoding="utf-8" ?>

<Images>

  <Image>
    <ImagePath>Images/1.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/2.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/3.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/4.jpg</ImagePath>
  </Image>

  <Image>
    <ImagePath>Images/5.jpg</ImagePath>
  </Image>
 
  
</Images>

Step 6
Create ImageEntity Class in App_Code Folder,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class ImageEntity
{
    #region Property

    public String ImagePath
    {
        get;
        set;
    }

    #endregion
}

Step 7
Add a Web service in the web application solution and give the name as WebServiceSlideShow.asmx,it's look like this




Click on Image for better View


Step 8
Now create a web method in web service for retrieving data from XML document.it is look like this 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Xml.Linq;

/// 
/// Summary description for WebServiceSlideShow
/// 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
 [System.Web.Script.Services.ScriptService]
public class WebServiceSlideShow : System.Web.Services.WebService {

    public WebServiceSlideShow () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public List<ImageEntity> GetImagesData()
    {
        try
        {
            // Load Xml Document  
            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/ImageData.xml"));

            // Query for retriving all Images data from XML  
            var Query = from Q in XDoc.Descendants("Image")
                        select new ImageEntity
                        {
                            ImagePath = Q.Element("ImagePath").Value
                        };

            // return images data  
            return Query.ToList<ImageEntity>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }
}

Note -  Uncomment the ScriptService attribute on the class to allow for JSON style results.


Now Code-behind part done.Let see the design and script part.


Step 9
First Drag and drop Image control on Div Tag,it is look like this
<div align="center">
        <asp:Image ID="ImgSlideShow" runat="server"/>      
</div>

Step 10
Create a CSS for Div Tag and Image Control inside the Head Tag,it is look like this
 

Step 11
Apply CSS on Div Tag and Image Control,it is look like this
<body>
    <form id="form1" runat="server">
    <div class="DivStyle" align="center">
        <asp:Image ID="ImgSlideShow" runat="server" CssClass="ImageStyle"   />      
    </div>
    </form>
</body>


Step 12
Add jQuery file Reference inside the head tag of the page,it is look like this
<script src="Scripts/jquery-1.6.4.min.js" type="text/javascript" language="javascript"></script>

Step 13
Add a below script inside the head tag.it is look like this
<script language="javascript" type="text/javascript">

        $(document).ready(function () {

            $.ajax(
                {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebServiceSlideShow.asmx/GetImagesData", // Specify the Webservice Name with Function name
                    data: "{}",
                    dataType: "json",
                    success: function (Data) {

                        // Get Images Data from Web Service
                        var ImagesData = Data.d;

                        // Get Length of Images
                        var ImagesLength = ImagesData.length; 

                        // Set First Loading Image to the Image Control
                        var ImageSlide = $("#ImgSlideShow"); // Pass ImageControl ID
                        ImageSlide.attr('src', 'images/Loading.gif');

                        // Set Interval of Images (Image Change in Every 3 Seconds)
                        setInterval(Slider, 3000); 

                        // Set Effect & Increment Images
                        function Slider() {

                            ImageSlide.fadeOut("slow", function () {

                                    $(this).attr('src', ImagesData[(ImagesData.length++) % ImagesLength].ImagePath).fadeIn("slow");
                                        
                            });

                        }

                    },
                    error: function (E) {
                        alert(e.message);
                    }

                }
            )
        }
        ); 

    </script>

It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties. 
type specifies the HTTP method, which in this case is POST. 
url specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property. In this case, no parameters are being passed, as we are calling the method that retrieves the entire collection of Images Path from XML Document. 
The contentType and dataType MUST be specified. 
Following this are two further functions: success defines what should be done if the call is successful, and error handles exceptions that are returned.


We then use the JavaScript setInterval() function which delays execution of the Slider function for a specific time, in our case 3000 millisecond(3 seconds). The advantage of a setInterval() function is that it continues to repeat the process of triggering the function at a specified interval, thereby sliding the images in a cycle.


Run the Project.


Output


Click on Image for better View

Full .Aspx Code

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Simple Image Slide Show Using JQuery</title>

    <style type="text/css">
    
        <%-- CSS for Div Tag--%>
        .DivStyle
        {
            background-color:transparent;
            width:820px; 
            margin-left:auto;
            margin-right:auto;
            padding:10px;
            border:solid 5px #c6cfe1;
            }
            
           <%-- CSS for Image Control--%>
            .ImageStyle
            {
                 margin-left:auto;
                 margin-right:auto;
                 padding:10px;
                 border:solid 1px #c6cfe1;
                 height:500px;
                width:800px;
                }
    
    </style> 

    <script src="Scripts/jquery-1.6.4.min.js" type="text/javascript" language="javascript"></script>  

    <script language="javascript" type="text/javascript">

        $(document).ready(function () {

            $.ajax(
                {
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "WebServiceSlideShow.asmx/GetImagesData", // Specify the Webservice Name with Function name
                    data: "{}",
                    dataType: "json",
                    success: function (Data) {

                        // Get Images Data from Web Service
                        var ImagesData = Data.d;

                        // Get Length of Images
                        var ImagesLength = ImagesData.length; 

                        // Set First Loading Image to the Image Control
                        var ImageSlide = $("#ImgSlideShow"); // Pass ImageControl ID
                        ImageSlide.attr('src', 'images/Loading.gif');

                        // Set Interval of Images (Image Change in Every 3 Seconds)
                        setInterval(Slider, 3000); 

                        // Set Effect & Increment Images
                        function Slider() {

                            ImageSlide.fadeOut("slow", function () {

                                    $(this).attr('src', ImagesData[(ImagesData.length++) % ImagesLength].ImagePath).fadeIn("slow");
                                        
                            });

                        }

                    },
                    error: function (E) {
                        alert(e.message);
                    }

                }
            )
        }
        ); 

    </script>  

</head>
<body>
    <form id="form1" runat="server">
    <div class="DivStyle" align="center">
        <asp:Image ID="ImgSlideShow" runat="server" CssClass="ImageStyle"   />      
    </div>
    </form>
</body>
</html>

Download
Download Source Code

Wednesday, September 21, 2011

MS-SQL - SQL Optimization Tips

• Use views and stored procedures instead of heavy-duty queries.
This can reduce network traffic, because your client will send to
server only stored procedure or view name (perhaps with some
parameters) instead of large heavy-duty queries text. This can be used
to facilitate permission management also, because you can restrict
user access to table columns they should not see.

• Try to use constraints instead of triggers, whenever possible.
Constraints are much more efficient than triggers and can boost
performance. So, you should use constraints instead of triggers,
whenever possible.

• Use table variables instead of temporary tables.
Table variables require less locking and logging resources than
temporary tables, so table variables should be used whenever possible.
The table variables are available in SQL Server 2000 only.

• Try to use UNION ALL statement instead of UNION, whenever possible.
The UNION ALL statement is much faster than UNION, because UNION ALL
statement does not look for duplicate rows, and UNION statement does
look for duplicate rows, whether or not they exist.

• Try to avoid using the DISTINCT clause, whenever possible.
Because using the DISTINCT clause will result in some performance
degradation, you should use this clause only when it is necessary.

• Try to avoid using SQL Server cursors, whenever possible.
SQL Server cursors can result in some performance degradation in
comparison with select statements. Try to use correlated sub-query or
derived tables, if you need to perform row-by-row operations.

• Try to avoid the HAVING clause, whenever possible.
The HAVING clause is used to restrict the result set returned by the
GROUP BY clause. When you use GROUP BY with the HAVING clause, the
GROUP BY clause divides the rows into sets of grouped rows and
aggregates their values, and then the HAVING clause eliminates
undesired aggregated groups. In many cases, you can write your select
statement so, that it will contain only WHERE and GROUP BY clauses
without HAVING clause. This can improve the performance of your query.

• If you need to return the total table's row count, you can use
alternative way instead of SELECT COUNT(*) statement.
Because SELECT COUNT(*) statement make a full table scan to return the
total table's row count, it can take very many time for the large
table. There is another way to determine the total row count in a
table. You can use sysindexes system table, in this case. There is
ROWS column in the sysindexes table. This column contains the total
row count for each table in your database. So, you can use the
following select statement instead of SELECT COUNT(*): SELECT rows
FROM sysindexes WHERE id = OBJECT_ID('table_name') AND indid < 2 So,
you can improve the speed of such queries in several times.

• Include SET NOCOUNT ON statement into your stored procedures to stop
the message indicating the number of rows affected by a T-SQL statement.
This can reduce network traffic, because your client will not receive
the message indicating the number of rows affected by a T-SQL statement.

• Try to restrict the queries result set by using the WHERE clause.
This can results in good performance benefits, because SQL Server will
return to client only particular rows, not all rows from the table(s).
This can reduce network traffic and boost the overall performance of
the query.

• Use the select statements with TOP keyword or the SET ROWCOUNT
statement, if you need to return only the first n rows.
This can improve performance of your queries, because the smaller
result set will be returned. This can also reduce the traffic between
the server and the clients.

• Try to restrict the queries result set by returning only the
particular columns from the table, not all table's columns.
This can results in good performance benefits, because SQL Server will
return to client only particular columns, not all table's columns.
This can reduce network traffic and boost the overall performance of
the query.
1.Indexes
2.avoid more number of triggers on the table
3.unnecessary complicated joins
4.correct use of Group by clause with the select list
5 In worst cases Denormalization


Index Optimization tips

• Every index increases the time in takes to perform INSERTS, UPDATES
and DELETES, so the number of indexes should not be very much. Try to
use maximum 4-5 indexes on one table, not more. If you have read-only
table, then the number of indexes may be increased.

• Keep your indexes as narrow as possible. This reduces the size of
the index and reduces the number of reads required to read the index.

• Try to create indexes on columns that have integer values rather
than character values.

• If you create a composite (multi-column) index, the order of the
columns in the key are very important. Try to order the columns in the
key as to enhance selectivity, with the most selective columns to the
leftmost of the key.

• If you want to join several tables, try to create surrogate integer
keys for this purpose and create indexes on their columns.

• Create surrogate integer primary key (identity for example) if your
table will not have many insert operations.

• Clustered indexes are more preferable than nonclustered, if you need
to select by a range of values or you need to sort results set with
GROUP BY or ORDER BY.

• If your application will be performing the same query over and over
on the same table, consider creating a covering index on the table.

• You can use the SQL Server Profiler Create Trace Wizard with
"Identify Scans of Large Tables" trace to determine which tables in
your database may need indexes. This trace will show which tables are
being scanned by queries instead of using an index.

• You can use sp_MSforeachtable undocumented stored procedure to
rebuild all indexes in your database. Try to schedule it to execute
during CPU idle time and slow production periods.
sp_MSforeachtable @command1="print '?' DBCC DBREINDEX ('?')"

Sunday, September 11, 2011

AJAX - Slide Show Extender

SlideShow is an extender that targets image controls. You can provide it with buttons to hit previous, next and play. You can configure the slideshow to play automatically on render, allow it loop through the images in a round robin fashion and also set the interval for slide transitions.


You can use a page method to supply images to the slide show or use a webservice.


In the sample above we have provided you with a slideshow that plays automatically on render and loops around to the first picture if you hit next on the last picture and vice versa if you hit previous on the first picture.


Let See how to create a dynamic Image slide show in ASP.net.


Step 1
Create a Web Application and give the solution name as SolAJAX_SlideShowExtender.


Step 2
Save images in Folder,Create a New Folder in the Solution and give folder name as Images,it is look like this


Click on image for better view


Step 3
Add XML file in the App_Data folder and give the file name as ImageData.xml,it is look like this




Click on image for better view


Step 4
The XML in the following example defines an XML document with a root node called Images. This root node contains one or more nodes called Image that include elements called ImageName and ImagePath,it's look like this


<?xml version="1.0" encoding="utf-8" ?>
<Images>

  <Image>
    <ImageName>Gaara</ImageName>
    <ImagePath>Images/Gaara.png</ImagePath>
  </Image>

  <Image>
    <ImageName>Choji Akimichi</ImageName>
    <ImagePath>Images/Choji.png</ImagePath>
  </Image>

  <Image>
    <ImageName>Jiraiya</ImageName>
    <ImagePath>Images/Jiraiya.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Kakashi Hatake</ImageName>
    <ImagePath>Images/Kakashi.png</ImagePath>
  </Image>

  <Image>
    <ImageName>Kiba Inuzuka</ImageName>
    <ImagePath>Images/Kiba.png</ImagePath>
  </Image>
  <Image>
    <ImageName>Naruto Uzumaki</ImageName>
    <ImagePath>Images/Naruto.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Neji Hyuuga</ImageName>
    <ImagePath>Images/Neji.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Rock Lee</ImageName>
    <ImagePath>Images/RockLee.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Sai</ImageName>
    <ImagePath>Images/Sai.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Shikamaru Nara</ImageName>
    <ImagePath>Images/Shikamaru.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Shino Aburame</ImageName>
    <ImagePath>Images/Shino.jpg</ImagePath>
  </Image>

  <Image>
    <ImageName>Yamato</ImageName>
    <ImagePath>Images/Yamato.jpg</ImagePath>
  </Image>

</Images>


Step 5
Create an ImageEntity class in App_Code Folder,it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

public class ImageEntity
{
    #region Property

    public String ImagePath
    {
        get;
        set;
    }

    public String ImageName
    {
        get;
        set;
    }

    #endregion
}


Step 6
Create a ImageView static class in a App_Code folder for retrieving data from XML document.it is look like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;

public static class ImageView
{
    #region Methods

   public static List<ImageEntity> GetAllImagesData()
    {
        try
        {
            // Load Xml Document

            XDocument XDoc = XDocument.Load(HttpContext.Current.Server.MapPath("~/App_Data/ImageData.xml"));

            // Query for retriving all Images data from XML
            var Query = from Q in XDoc.Descendants("Image")
                        select new ImageEntity
                        {
                            ImagePath = Q.Element("ImagePath").Value,
                            ImageName=Q.Element("ImageName").Value   
                        };

            // return images data
            return Query.ToList<ImageEntity>();

        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);
        }
    }

    #endregion
}

Step 7
Add a ToolkitScriptManager control from Ajax toolkit inside the Div Tag,it is look like this
<div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>
</div>

This control allows you to replace the default <asp:scriptmanager> control behavior, and supports the ability to dynamically merge multiple client-side Javascript scripts into a single file that is downloaded to the client at runtime. 


Step 8
Now design page for slide show,it is look like this
<div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
            
               
                <table border="0" cellpadding="5" cellspacing="3" width="50%" align="center">
                    <tr>
                        <td colspan="3">
                            <asp:Image ID="ImageSlide" runat="server" Width="400px" Height="400px" 
                                BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="2px" />     
                         </td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center" valign="middle">
                            <asp:Label ID="LblImageName" runat="server" Font-Bold="True" Font-Size="Large" 
                                ForeColor="#666666"></asp:Label>   
                        </td>
                    </tr>
                    <tr>
                        <td align="center" valign="middle">
                            <asp:Button ID="BtnPrevious" runat="server" Text="Previous" Width="100px"  />  
                        </td>
                        <td align="center" valign="middle">
                            <asp:Button ID="BtnPlay" runat="server" Text="Play" Width="100px"   />
                            </td>
                        <td align="center" valign="middle">
                            <asp:Button ID="BtnNext" runat="server" Text="Next"  Width="100px"  />
                        </td>
                    </tr>
                </table>

                
                

            </ContentTemplate> 
        </asp:UpdatePanel>   
    </div>



Click on image for better view


Step 9
Add Extender to the Image control,it is look like this




Click on image for better view


Click on Add Extender link and Extender Wizard dialog box will be open and select SlideShowExtender and click on OK button.




Click on image for better view


AJAX SlideShowExtender Properties



  1. TargetControlID 
    • ID of the Image control to display the images of SlideShow program.
  2. AutoPlay
    • Enables the feature to start to SlideShow automatically when page loads.
  3. ImageTitleLabelID
    • ID of the Label control to display the Title/Name of the image.
  4. PreviousButtonID
    • ID of the button that will allow you to see the previous picture.
  5. PlayButtonID 
    • ID of the button that will allow you to play/stop the slideshow.
  6. NextButtonID
    • ID of the button that will allow you to see the next picture.
  7. PlayButtonText 
    • The text to be shown in the play button to play the slideshow.
  8. StopButtonText
    • The text to be shown in the play button to stop the slideshow.
  9. PlayInterval 
    • Interval in milliseconds between slide transitions in play mode.
  10. Loop
    • Setting this to true will allow you to view images in a round-robin fashion.
  11. SlideShowServiceMethod
    • Name of the page script web service method to pass the array of Slide Show images.
    • You can use any method name for WebMethod but its return type should be of AjaxControlToolkit.Slide[].
<asp:Image ID="ImageSlide" runat="server" Width="400px" Height="400px" 
                                BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="2px" />     
    
                           <asp:SlideShowExtender ID="ImageSlide_SlideShowExtender" runat="server" 
                                Enabled="True" SlideShowServiceMethod="GetSlides" SlideShowServicePath="" 
                               TargetControlID="ImageSlide" AutoPlay="true" ImageTitleLabelID="LblImageName"
                    PreviousButtonID="BtnPrevious" PlayButtonID="BtnPlay" NextButtonID="BtnNext" 
                    PlayButtonText="Play" StopButtonText="Stop" PlayInterval="1000"
                    Loop="true">
                            </asp:SlideShowExtender>


Step 10
Add a Service method in code behind.Expanding the Image control smart tag,select the add SlideShow page method option from the provided menu.This action create a service method in code behind for your page,it is look like this




Click on image for better view


Note: Remove the ContextKey parameter from GetSlides method. 


Step 11
The SlideShow requires a PageMethod called GetSlides that will be called to supply images from XML document,it is look like this.
[System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static AjaxControlToolkit.Slide[] GetSlides()
    {
        try
        {
            // Store imgaes data into List 
           List<ImageEntity> ImageEntityObj = ImageView.GetAllImagesData();

            // Declaration of array of Slide
            AjaxControlToolkit.Slide[] SlideImages = null;

            // Check the ImageEntity null or not
            if (ImageEntityObj != null)
            {
                // Check the count of ImageEntity
                if (ImageEntityObj.Count > 0)
                {
                    // Create a Instance of array of Slide
                    SlideImages = new AjaxControlToolkit.Slide[ImageEntityObj.Count];

                    // Bind Image path and Name
                    for (int i = 0; i < ImageEntityObj.Count; i++)
                    {
                        SlideImages[i] = new AjaxControlToolkit.Slide(ImageEntityObj[i].ImagePath, ImageEntityObj[i].ImageName, String.Empty);
                    }
                }
            }

            return SlideImages; 
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message); 
        }
    }


Run the Project.


Output




Full .ASPX Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
        </asp:ToolkitScriptManager>

        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
            
               
                <table border="0" cellpadding="5" cellspacing="3" width="50%" align="center">
                    <tr>
                        <td colspan="3">
                            <asp:Image ID="ImageSlide" runat="server" Width="400px" Height="400px" 
                                BorderColor="#CCCCCC" BorderStyle="Solid" BorderWidth="2px" />     
    
                           <asp:SlideShowExtender ID="ImageSlide_SlideShowExtender" runat="server" 
                                Enabled="True" SlideShowServiceMethod="GetSlides" SlideShowServicePath="" 
                               TargetControlID="ImageSlide" AutoPlay="true" ImageTitleLabelID="LblImageName"
                    PreviousButtonID="BtnPrevious" PlayButtonID="BtnPlay" NextButtonID="BtnNext" 
                    PlayButtonText="Play" StopButtonText="Stop" PlayInterval="1000"
                    Loop="true" UseContextKey="True">
                            </asp:SlideShowExtender>
    
                         </td>
                    </tr>
                    <tr>
                        <td colspan="3" align="center" valign="middle">
                            <asp:Label ID="LblImageName" runat="server" Font-Bold="True" Font-Size="Large" 
                                ForeColor="#666666"></asp:Label>   
                        </td>
                    </tr>
                    <tr>
                        <td align="center" valign="middle">
                            <asp:Button ID="BtnPrevious" runat="server" Text="Previous" Width="100px"  />  
                        </td>
                        <td align="center" valign="middle">
                            <asp:Button ID="BtnPlay" runat="server" Text="Play" Width="100px"   />
                            </td>
                        <td align="center" valign="middle">
                            <asp:Button ID="BtnNext" runat="server" Text="Next"  Width="100px"  />
                        </td>
                    </tr>
                </table>

                
                

            </ContentTemplate> 
        </asp:UpdatePanel>   
    </div>
    </form>
</body>
</html>


Download
Download Source Code


Thursday, September 1, 2011

JQuery - TextBox Style on Focus using JQuery

In this article i will show you how to change style of ASP.net Textbox control using JQuery.


Step 1
Download JQuery Script from the following Link
http://code.jquery.com/jquery-1.6.1.min.js



Step 2
Create a Web Application and give the Solution name as SolTextBoxStyleonFocus_JQuery



Step 3
Create a sample form and apply the Focus effect using jQuery,it is look like this
<form id="form1" runat="server">
    <div>
       <table border="0" cellpadding="10" cellspacing="5" width="40%" align="center">
            <tr>
                <td>First Name</td>
                <td>
                    <asp:TextBox ID="TxtFirstName" runat="server"></asp:TextBox> 
                </td>
               
            </tr>
            <tr>
                <td>Last Name</td>
                <td>
                    <asp:TextBox ID="TxtLastName" runat="server"></asp:TextBox> 
                </td>
                
            </tr>
            <tr>
                <td>Age</td>
                <td>
                    <asp:TextBox ID="TxtAge" runat="server"></asp:TextBox> 
                </td>
               
            </tr>
       </table> 
    </div>
    </form>

Step 4
Add jQuery file Reference inside the head tag of the page,it is look like this

 


Step 5
Create a 
style class inside the head tag to apply to the focused field,it is look like this

Step 6
Write  jQuery script to add effect to the form elements. Two events has to be taken care of. While the input field is focused and while the focus is moved to next textbox (blured),it is look like this
 


Run the Project.


Output


Click on image for better view


Full .Aspx code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>TextBox Style on Focus using Jquery</title>

    <style type="text/css">
    
        .TxtBoxFocus
        {
            border:2px solid Orange;
            background-color:Silver;
            
            }
    
    </style>


    <script src="Scripts/jquery-1.6.1.min.js" language="javascript" type="text/javascript"></script> 

    <script language="javascript" type="text/javascript">

        $(document).ready(function () {

            // On Focus

            $('input[type="text"]').focus(function () {

                $(this).addClass("TxtBoxFocus");

            });

            // On Blur 

            $('input[type="text"]').blur(function () {

                $(this).removeClass("TxtBoxFocus");

            });


        });

    </script> 

</head>
<body>
    <form id="form1" runat="server">
    <div>
       <table border="0" cellpadding="10" cellspacing="5" width="40%" align="center">
            <tr>
                <td>First Name</td>
                <td>
                    <asp:TextBox ID="TxtFirstName" runat="server"></asp:TextBox> 
                </td>
               
            </tr>
            <tr>
                <td>Last Name</td>
                <td>
                    <asp:TextBox ID="TxtLastName" runat="server"></asp:TextBox> 
                </td>
                
            </tr>
            <tr>
                <td>Age</td>
                <td>
                    <asp:TextBox ID="TxtAge" runat="server"></asp:TextBox> 
                </td>
               
            </tr>
       </table> 
    </div>
    </form>
</body>
</html>


Download
Download Source Code