Create a Simple Image Slide Show using jQuery

I have seen a lot of users requesting for simple jQuery scripts for SlideShows. I saw a couple of them, but the scripts assumed that the number of image tags has to be fixed beforehand.

Update: There is a updated version of this article at Simple Image SlideShow using jQuery

I thought of making an attempt at a real simple SlideShow script using jQuery. Here’s what I came up with 5 lines of jQuery code. The images have been added to a ‘images’ folder kept at the root. The images has been defined in an array which can be retrieved from a server. For simplicity sake, I have harcoded the images paths, however the script functionality can adapt dynamically to the number of images in the array.

<!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>
<
title>Simple Slide Show with jQuery</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>
<
script type="text/javascript">
var
imgs = [
'images/emo.jpg',
'images/icon068.gif',
'images/icon260.jpg'];
var cnt = imgs.length;

$(function() {
setInterval(Slider, 3000);
});

function Slider() {
$('#imageSlide').fadeOut("slow", function() {
$(this).attr('src', imgs[(imgs.length++) % cnt]).fadeIn("slow");
});
}
</script>
</
head>
<
body>
<
img id="imageSlide" alt="" src="" />
</
body>
</
html>

The code is not perfect but will give you an idea of how to extend this sample to suit your own requirements. You can see a Live Demo here.

Retrieve Rows Selected Using CheckBox in an ASP.NET GridView

I bet you must have seen this question asked a several times ‘How Can I find out which Checkboxes were selected in a GridView. I also want to retrieve row data for these selected rows on Postback’.

I personally have seen this question hundreds of times on the forums, newsgroups. If you have been facing this requirement, here’s a full working example for you to try out. This example binds the GridView to a List<>

<!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>Get Selected Rows during PostBack</title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" >
<
Columns>
<
asp:TemplateField>
<
ItemTemplate>
<
asp:CheckBox ID="chkSel" runat="server" />
</
ItemTemplate>
</
asp:TemplateField>
<
asp:BoundField DataField="ID" HeaderText="EmployeeId"
SortExpression="EmployeeId" />
<
asp:BoundField DataField="FName" HeaderText="FirstName"
SortExpression="FirstName" />
<
asp:BoundField DataField="Age" HeaderText="Age"
SortExpression="Age" />
<
asp:BoundField DataField="Sex" HeaderText="Sex"
SortExpression="Sex" />
</
Columns>
</
asp:GridView>
<
br />
<
asp:Button ID="btnRetrieveCheck" runat="server"
Text="Retrieve Checked Items" onclick="btnRetrieveCheck_Click" />
</
div>
</
form>
</
body>
</
html>



Points to observe:

- The AutoGenerateColumns of the GridView is set to false

- The CheckBox has been added inside an ItemTemplate

- DataKeyName of the GridView is set to ID.

C#

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default4 : System.Web.UI.Page
{
List<Employee> listEmp = new List<Employee>();

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Employee emp = new Employee();
listEmp = emp.GetEmployees();
this.GridView1.DataSource = listEmp;
this.GridView1.DataBind();
}
}

protected void btnRetrieveCheck_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSel");
if (cb != null && cb.Checked)
{
Response.Write("Employee Id: " +
GridView1.DataKeys[row.RowIndex].Value
+ " Name: " + row.Cells[2].Text + "<br/>");
}
}
}
}

public class Employee
{

public int ID { get; set; }

public string FName { get; set; }

public int Age { get; set; }

public char Sex { get; set; }

public List<Employee> GetEmployees()
{
List<Employee> eList = new List<Employee>();

eList.Add(new Employee() { ID = 1, FName = "John", Age = 23, Sex = 'M' });

eList.Add(new Employee() { ID = 2, FName = "Mary", Age = 25, Sex = 'F' });

eList.Add(new Employee() { ID = 3, FName = "Amber", Age = 23, Sex = 'M' });

eList.Add(new Employee() { ID = 4, FName = "Kathy", Age = 25, Sex = 'M' });

eList.Add(new Employee() { ID = 5, FName = "Lena", Age = 27, Sex = 'F' });

eList.Add(new Employee() { ID = 6, FName = "John", Age = 28, Sex = 'M' });

eList.Add(new Employee() { ID = 7, FName = "Kathy", Age = 27, Sex = 'F' });

eList.Add(new Employee() { ID = 8, FName = "John", Age = 28, Sex = 'M' });

return eList;
}


}

VB.NET

Imports System
Imports System.Collections.Generic
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class Default4
Inherits System.Web.UI.Page
Private listEmp As New List(Of Employee)()

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not Page.IsPostBack) Then
Dim
emp As New Employee()
listEmp = emp.GetEmployees()
Me.GridView1.DataSource = listEmp
Me.GridView1.DataBind()
End If
End Sub

Protected Sub
btnRetrieveCheck_Click(ByVal sender As Object, _
ByVal e As EventArgs)
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = CType(row.FindControl("chkSel"), CheckBox)
If cb IsNot Nothing AndAlso cb.Checked Then
Response.Write("Employee Id: " & _
GridView1.DataKeys(row.RowIndex).Value & " Name: " & _
row.Cells(2).Text & "<br/>")
End If
Next
row
End Sub
End Class
Public Class Employee

Private privateID As Integer
Public Property
ID() As Integer
Get
Return
privateID
End Get
Set
(ByVal value As Integer)
privateID = value
End Set
End Property

Private
privateFName As String
Public Property
FName() As String
Get
Return
privateFName
End Get
Set
(ByVal value As String)
privateFName = value
End Set
End Property

Private
privateAge As Integer
Public Property
Age() As Integer
Get
Return
privateAge
End Get
Set
(ByVal value As Integer)
privateAge = value
End Set
End Property

Private
privateSex As Char
Public Property
Sex() As Char
Get
Return
privateSex
End Get
Set
(ByVal value As Char)
privateSex = value
End Set
End Property

Public Function
GetEmployees() As List(Of Employee)
Dim eList As New List(Of Employee)()

eList.Add(New Employee() With {.ID = 1,.FName = "J",.Age = 23,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 2,.FName = "M",.Age = 25,.Sex = "F"c})

eList.Add(New Employee() With {.ID = 3,.FName = "A",.Age = 23,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 4,.FName = "K",.Age = 25,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 5,.FName = "L",.Age = 27,.Sex = "F"c})

eList.Add(New Employee() With {.ID = 6,.FName = "J",.Age = 28,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 7,.FName = "K",.Age = 27,.Sex = "F"c})

eList.Add(New Employee() With {.ID = 8,.FName = "J",.Age = 28,.Sex = "M"c})

Return eList
End Function


OUTPUT
image 

Retrieve Data From a Table Cell Using jQuery

I have seen a lot of users asking questions on how to retrieve information when the the cell of a Table is clicked. In this post, I will show how to retrieve the following information from a Table Cell that was clicked

  • - Retrieve Text of the Clicked Cell
  • - Retrieve Text to the Left of the Clicked Cell
  • - Retrieve Text to the Right of the Clicked Cell
  • - Retrieve Row Index of the Clicked Cell
  • - Retrieve Column Index of the Clicked Cell
  • - Retrieve Number of Rows above the Current Clicked Row
  • - Retrieve Column Name of the Clicked Cell
<!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>
<
title>How to retrieve information from cell clicked in a Table</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'></script>
<
script type="text/javascript">
$(document).ready(function() {
$("tbody td").click(function(e) {
var currentCellText = $(this).text();
var LeftCellText = $(this).prev().text();
var RightCellText = $(this).next().text();
var RowIndex =$(this).parent().parent().children().index($(this).parent());
var ColIndex = $(this).parent().children().index($(this));
var RowsAbove = RowIndex;
var ColName = $(".head").children(':eq(' + ColIndex + ')').text();


$("#para").text('')
.append("<b>Current Cell Text: </b>" + currentCellText + "<br/>")
.append("<b>Text to Left of Clicked Cell: </b>" + LeftCellText + "<br/>")
.append("<b>Text to Right of Clicked Cell: </b>" + RightCellText + "<br/>")
.append("<b>Row Index of Clicked Cell: </b>" + RowIndex + "<br/>")
.append("<b>Column Index of Clicked Cell: </b>" + ColIndex + "<br/>")
.append("<b>Rows above Current Clicked Row: </b>" + RowsAbove + "<br/>")
.append("<b>Column Name of Clicked Cell: </b>" + ColName)

});
});

</script>
<
style type="text/css">
body
{
font-family:Garamond;
}
</style>
</
head>
<
body>
<
table id="tableone" border="1">
<
thead>
<
tr class="head">
<
th>Column 1</th>
<
th>Column 2</th>
<
th>Column 3</th>
</
tr>
</
thead>
<
tbody>
<
tr >
<
td>Row 0 Column 0</td>
<
td >Row 0 Column 1</td>
<
td >Row 0 Column 2</td>
</
tr>
<
tr >
<
td>Row 1 Column 0</td>
<
td>Row 1 Column 1</td>
<
td>Row 1 Column 2</td>
</
tr>
<
tr >
<
td>Row 2 Column 0</td>
<
td>Row 2 Column 1</td>
<
td>Row 2 Column 2</td>
</
tr>
<
tr >
<
td>Row 3 Column 0</td>
<
td>Row 3 Column 1</td>
<
td>Row 3 Column 2</td>
</
tr>
<
tr >
<
td>Row 4 Column 0</td>
<
td>Row 4 Column 1</td>
<
td>Row 4 Column 2</td>
</
tr>
<
tr >
<
td>Row 5 Column 0</td>
<
td>Row 5 Column 1</td>
<
td>Row 5 Column 2</td>
</
tr>
</
tbody>
</
table>
<
p id="para" />

</
body>
</
html>



Output

image


See a Live Demo here.

Find the Position of an Element using jQuery

One of my colleagues recently asked me the right way to find the position of an element on the page using jQuery. In my opinion the right way to this in jQuery is to use position() which fetches the top and left position of an element relative to its offset parent. Here’s an example of how to find the position of the Lower Div :

<!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>
<
title>Find the position of an element in jQuery</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'></script>
<
script type='text/javascript'>
$(function() {
$("#para").append("Top: " + $('#Lower').position().top + "<br/>")
.append("Left: " + $('#Lower').position().left);
});
</script>

<
style type="text/css">
div
{
border:solid 1px Silver;
background-color:Gray;
}
</style>
</
head>
<
body>
<
div id="Upper">
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
upper upper upper upper upper upper upper upper upper upper upper upper
</div>
<
br />
<
div id="Lower">
lower lower lower lower lower lower lower lower lower lower lower lower
lower lower lower lower lower lower lower lower lower lower lower lower
lower lower lower lower lower lower lower lower lower lower lower lower
lower lower lower lower lower lower lower lower lower lower lower lower
lower lower lower lower lower lower lower lower lower lower lower lower
lower lower lower lower lower lower lower lower lower lower lower lower
</div>

<
p id="para" />
</
body>
</
html>



OUTPUT


image

Retrieve Selected Items of an ASP.NET ListBox using LINQ

I had recently written a post on Programmatically Select Multiple Items of an ASP.NET ListBox. A user ‘JukeBox’ mailed back asking me if it was possible to retrieve the selected items of a ListBox using LINQ. Here’s how to do so:

<div>
<
asp:ListBox ID="ListBox1" runat="server" SelectionMode="Multiple">
<
asp:ListItem Value="One" Selected="True" />
<
asp:ListItem Value="Two" />
<
asp:ListItem Value="Three" />
<
asp:ListItem Value="Four" Selected="True" />
<
asp:ListItem Value="Five" />
</
asp:ListBox>
<
br />
<
br />
<
asp:Button ID="btnSel" runat="server" Text="Get Selected"
onclick="btnSel_Click" />
</
div>

C#

protected void btnSel_Click(object sender, EventArgs e)
{
var selItems = from ListItem li in ListBox1.Items
where li.Selected == true
select
li.Text;

Response.Write("Selected Item(s): </br>");
foreach (var item in selItems)
{
Response.Write(item.ToString() + "</br>");
}
}

VB.NET

Protected Sub btnSel_Click(ByVal sender As Object, ByVal e As EventArgs)
Dim selItems = _
From li As ListItem In ListBox1.Items _
Where li.Selected = True _
Select li.Text

Response.Write("Selected Item(s): </br>")
For Each item In selItems
Response.Write(item.ToString() & "</br>")
Next item
End Sub

On clicking the Button, the selected items are fetched as shown below:

image

Programmatically Select Multiple Items of an ASP.NET ListBox

In one of the forums, a user recently asked how to select multiple items of an ASP.NET ListBox. Here’s how

<div>
<
asp:ListBox ID="ListBox1" runat="server">
<
asp:ListItem Value="One" />
<
asp:ListItem Value="Two" />
<
asp:ListItem Value="Three" />
<
asp:ListItem Value="Four" />
<
asp:ListItem Value="Five" />
</
asp:ListBox>
</
div>

C#

protected void Page_Load(object sender, EventArgs e)
{
ListBox1.SelectionMode = ListSelectionMode.Multiple;
for (int i = 0; i < ListBox1.Items.Count; i++)
{
if(i == 0 || i == 2 || i == 4)
{
ListBox1.Items[i].Selected = true;
}
}
}

VB.NET

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
ListBox1.SelectionMode = ListSelectionMode.Multiple
For i As Integer = 0 To ListBox1.Items.Count - 1
If i = 0 OrElse i = 2 OrElse i = 4 Then
ListBox1.Items(i).Selected = True
End If
Next
i
End Sub

The code shown above selects the first, third and fifth items of a ListBox as in the screenshot below

image

Detect any Event on an Element using jQuery

The jQuery event.type is very useful when you want to detect the nature of an event on an Element and determine if it was a click, doubleclick, mousemove, mouseenter and so on. Here’s how to detect the Event Type on an Element with minimal code in jQuery

<!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>
<
title>Detect any event</title>

<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$('.someDiv').bind('click dblclick mousedown mouseenter mouseleave',
detectEvent);

function detectEvent(e) {
$('.para').text('Current Event is: ' + e.type);
}
});
</script>
<
style type="text/css">
.someDiv
{
height:400px;
width:400px;
background-color:Gray;
}
.para
{
background-color:Black;
color:White;
}
</style>
</
head>
<
body>
<
div>
<
div class="someDiv"/>
<
p class="para" />
</
div>

</
body>
</
html>

Live Demo

To test the functionality, run the piece of code shown above and perform a click, doubleclick, mousemove, mouseenter and so on on the Gray area

Find out which Key was pressed using jQuery

A user had a requirement to take actions on a page based on the KeyPressed. Here’s a simple script that you can do that and works cross-browser.

<html xmlns="http://www.w3.org/1999/xhtml" >
<
head>
<
title>Find KeyPressed</title>

<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$(this).bind('keypress', function(e) {
var key = (e.keyCode ? e.keyCode : e.charCode);
alert(key);
});
});
</script>
</
head>
<
body>
<
div>
</
div>
</
body>
</
html>



You can also use ‘e.which’ instead of ‘e.charCode’. I have tested the code on IE7, Chrome and Firefox 3.

To do the same on an ASP.NET page, check my article over here Implementing KeyBoard Shortcuts in ASP.NET applications using jQuery

How to add CSS Programmatically to an ASP.NET Page

I recently wrote an article on How to add a CSS Link programmatically using JavaScript. A user asked me how to do it in an ASP.NET page. It’s quite simple actually using the HtmlLink class which gives you programmatic access to the HTML <link> element.

Start by adding a reference to the System.Web.UI.HtmlControls namespace. Also make sure that your head tag has the runat=”server” attribute

<head runat="server">
<
title>Add CSS Dynamically</title>
</
head>

Then add the following code in your code behind.

C#

protected void Page_Init(object sender, EventArgs e)
{
HtmlLink link = new HtmlLink();
link.Href = "~CSS/FloatDes.css";
link.Attributes.Add("rel", "stylesheet");
link.Attributes.Add("type", "text/css");
Page.Header.Controls.Add(link);
}

VB.NET

Protected Sub Page_Init(ByVal sender As Object, ByVal e As EventArgs)
Dim link As New HtmlLink()
link.Href = "~CSS/FloatDes.css"
link.Attributes.Add("rel", "stylesheet")
link.Attributes.Add("type", "text/css")
Page.Header.Controls.Add(link)
End Sub

Now run your page and check it’s source. You will see the link to the CSS file added in the head element as shown below:

<head><title>

Add CSS Dynamically

</title><link href="~CSS/FloatDes.css" rel="stylesheet" type="text/css" /></head>

Expression Studio 3 Released – Some Important Links

The wait ends. Expression Studio 3 is now available for a Free 60 days trial.

Microsoft Expression Studio opens up a new world of creative possibility. Its professional design tools give you the freedom to make your vision real—whether you’re designing for standards-based Web sites, rich desktop experiences, or Silverlight. Includes Expression Web, Expression Blend, Expression Design and Expression Encoder. The Expression Studio 3 Suite consists of the following products

  • Expression Blend™ 3
  • SketchFlow
  • Expression Web 3
  • Expression Design 3
  • Expression Encoder 3

    Note: Expression Blend 3 was released as a trial some time ago.

    Here are some important links:

  • Top 10 Features of Expression Studio 3

  • Expression Studio 3 Free Trial – Links to all the products in the Expression 3 Suite

  • Expression Studio 3 Pre-Order

  • Expression Studio 3 Overview Video

  • How to add a CSS Link programmatically using JavaScript

    In one of my earlier posts, I demonstrated how to Programmatically Retrieve StyleSheet Url’s Referenced in your Page using JavaScript. In this post, here’s a piece of JavaScript code that demonstrates how you can programmatically reference a CSS link on a page.

    <html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    title></title>
    <
    link href="CSS/FloatDes.css" rel="stylesheet"
    title="Float layout" type="text/css" />

    <
    script type="text/javascript">
    function
    addCSS() {
    var headtg = document.getElementsByTagName('head')[0];
    if (!headtg) {
    return;
    }
    var linktg = document.createElement('link');
    linktg.type = 'text/css';
    linktg.rel = 'stylesheet';
    linktg.href = 'CSS/RoundCorners.css';
    linktg.title = 'Rounded Corners';
    headtg.appendChild(linktg);
    }
    </script>
    </
    head>
    <
    body onload="addCSS()">

    </
    body>
    </
    html>


    The code shown above creates a link element(with properties) and appends it as a child to the &lt;head&gt; section. You can use this technique to let users choose styles and change the appearance of the page.

    Programmatically Retrieve StyleSheet Url’s Referenced in your Page using JavaScript

    I came across a requirement where the stylesheets referenced by a page had to be listed. The user was then given the ability to disable the stylesheet he did not want. Here’s how we can use the document.styleSheets collection to retrieve the collection of styleSheet objects that are referenced using a &lt;link&gt; and then disable the stylesheet the user does not desire. A portion of the code is as given here:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <
    head>
    <
    title></title>
    <
    link href="CSS/FloatDes.css" rel="stylesheet"
    title="Float layout" type="text/css" />
    <
    link href="CSS/RoundCorners.css" rel="stylesheet"
    title="Rounded Corners" type="text/css" />

    <
    script type="text/javascript">
    for
    (i = 0; i < document.styleSheets.length; i++) {
    alert(document.styleSheets[i].title);
    alert(document.styleSheets[i].href);
    }
    </script>
    </
    head>
    <
    body>

    </
    body>
    </
    html>



    Similarly, if you have imported stylesheets using @import, you can access the style sheets using document.styleSheets[i].imports.

    To disable a stylesheet programmatically, use this piece of code:

    document.styleSheets[i].disabled = true;

    To check if the styleSheet collection is supported on your browser, use this :

     if (typeof document.styleSheets != "undefined")



    This code has been tested on IE7 and Firefox 3

    FireFox 3.5.1 has been released

    FireFox 3.5.1 was released on July 16th 2009 to fix several security and stability issues. One of the major bug fixes was for a security issue with the software's browser's TraceMonkey JavaScript engine. Mozilla is one of its comments had stated "Just-In-Time" (JIT) compiler used for JavaScript. A crash could result in an exploitable memory corruption problem that could, under certain cases, be exploited by an attacker to run arbitrary code, like malware”. This release also speeds up launch time on some Windows systems.

    Here are some important links for this release

    Security Issues fixed in FireFox 3.5.1

    List of changes in FireFox 3.5.1

    Firefox 3.5 release notes

    The latest version of FireFox can be downloaded over here

    Sort Items in an ASP.NET DropDownList using LINQ

    Have you been looking out for a way to sort the items of an ASP.NET DropDownList using LINQ? Here’s a LINQ solution:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <
    head runat="server">
    <
    title>Sorting DropDownList Items</title>
    </
    head>
    <
    body>
    <
    form id="form1" runat="server">
    <
    div>
    <
    asp:DropDownList ID="DropDownList1" runat="server">
    <
    asp:ListItem Text="Item3"></asp:ListItem>
    <
    asp:ListItem Text="Item1"></asp:ListItem>
    <
    asp:ListItem Text="Item4"></asp:ListItem>
    <
    asp:ListItem Text="Item5"></asp:ListItem>
    <
    asp:ListItem Text="Item2"></asp:ListItem>
    </
    asp:DropDownList>
    <
    br />
    <
    asp:Button ID="btnSort" runat="server" Text="Sort"
    onclick="btnSort_Click"/>
    </
    div>
    </
    form>
    </
    body>
    </
    html>



    C#

    protected void btnSort_Click(object sender, EventArgs e)
    {
    List<string> listItems =
    DropDownList1.Items.Cast<ListItem>().Select(item => item.Text).ToList();
    listItems.Sort((a, b) => string.Compare(a, b));
    DropDownList1.DataSource = listItems;
    DropDownList1.DataBind();
    }

    VB.NET

    Protected Sub btnSort_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim listItems As List(Of String) = _
    DDL.Items.Cast(Of ListItem)().Select(Function(item) item.Text).ToList()
    listItems.Sort(Function(a, b) String.Compare(a, b))
    DDL.DataSource = listItems
    DDL.DataBind()
    End Sub

    Before Sorting

    image

    After Sorting

    image

    Search an ASP.NET DropDownList

    A user mailed me recently asking me the simplest way to search an ASP.NET DropDownList. I think the simplest way is using the foreach loop as shown below (although it may be slow when the items are huge):

    <html xmlns="http://www.w3.org/1999/xhtml">
    <
    head runat="server">
    <
    title></title>
    </
    head>
    <
    body>
    <
    form id="form1" runat="server">
    <
    div>
    <
    asp:DropDownList ID="DropDownList1" runat="server">
    <
    asp:ListItem Text="Item1"></asp:ListItem>
    <
    asp:ListItem Text="Item2"></asp:ListItem>
    <
    asp:ListItem Text="Item3"></asp:ListItem>
    </
    asp:DropDownList>
    <
    br />
    <
    asp:Button ID="btnSearch" runat="server" Text="Search"
    onclick="btnSearch_Click"/>
    </
    div>
    </
    form>
    </
    body>
    </
    html>

    C#

    protected void btnSearch_Click(object sender, EventArgs e)
    {
    string str = "Item2";
    // Using For Each
    foreach (ListItem li in DropDownList1.Items)
    {
    if (li.Value == str)
    {
    this.DropDownList1.SelectedValue = li.Value.ToLower();

    }
    }
    }

    VB.NET

    Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim str As String = "Item2"
    ' Using For Each
    For Each li As ListItem In DropDownList1.Items
    If li.Value = str Then
    Me
    .DropDownList1.SelectedValue = li.Value.ToLower()

    End If
    Next
    li
    End Sub
    The code shown above loops through all the items of a DropDownList and selects the item if the string is found. To make the code case insensitive, use ToLower()/ToUpper() and compare the values.

    Access an ASP.NET control on a MasterPage using jQuery

    I must have been asked this question numerous times -- How do I access an asp.net control kept in the master page using jQuery? Here’s one of the ways of how to populate the value of an ASP.NET TextBox kept in a MasterPage using jQuery

    MasterPage

    <%@ Master Language="C#" AutoEventWireup="true"
    CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

    <!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>Access Control using jQuery</title>
    <
    asp:ContentPlaceHolder id="head" runat="server">
    </
    asp:ContentPlaceHolder>

    <
    script src="Scripts/jquery-1.3.2.js"
    type="text/javascript"></script>
    <
    script type="text/javascript">
    $(document).ready(function() {
    $("input[id$='txtName']").val("Text Added using jQuery");
    });
    </script>
    </
    head>
    <
    body>
    <
    form id="form1" runat="server">
    <
    div>
    <
    asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">

    </
    asp:ContentPlaceHolder>
    </
    div>
    </
    form>
    </
    body>
    </
    html>



    ContentPage

    <%@ Page Language="C#" MasterPageFile="~/MasterPage.master"

    AutoEventWireup="true" CodeFile="MasterPage.aspx.cs" Inherits="MasterPage"%>

    <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">

    </
    asp:Content>

    <
    asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1"

    Runat="Server">

    <
    asp:TextBox ID="txtName" runat="server"></asp:TextBox>

    </
    asp:Content>

    Note how we selected the MasterPage using the $("input[id$='txtName']") . This is because the TextBox in the MasterPage gets renamed as shown below:

    <input name="ctl00$ContentPlaceHolder1$txtName" type="text" id="ctl00_ContentPlaceHolder1_txtName" />

    On running the page, the textbox gets populated using jQuery

    image

    Check out my other ASP.NET jQuery articles.

    Convert all Links to Open in a New Page

    I was working on an existing website recently. The website had a few pages with a couple of hyperlinks leading to Customers websites. Clicking on the hyperlink would renders the content in the same window. The client now wanted that without any code change, all the links should open in a new window, so that the user remains on the main site, as well as also view the Customers website.

    Here’s how this requirement can be achieved using jQuery

    <!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>
    <
    title>Open all Links In New Window</title>

    <
    script src="Scripts/jquery-1.3.2.js"
    type="text/javascript"></script>
    <
    script type="text/javascript">
    $(document).ready(function() {
    $("a").each(function() {
    $(this).attr("target", "_blank");
    });
    });
    </script>
    </
    head>
    <
    body>
    <
    div>
    <
    a href="http://www.dotnetcurry.com">DotNetCurry</a><br />
    <
    a href="http://www.sqlservercurry.com">SQL Server</a><br />
    <
    a href="http://www.devcurry.com">DevCurry</a><br />
    </
    div>
    <
    br />
    </
    body>
    </
    html>


    Observe that using jQuery, we set the target property of all the hyperlink to _blank, which renders content in a new window. Here are the values of the Target property

    _blank - Renders the content in a new window without frames.

    _parent - Renders the content in the immediate frameset parent.

    _self - Renders the content in the frame with focus.

    _top - Renders the content in the full window without frames

    If you want to achieve the same in an ASP.NET page, just replace the links with an ASP.NET Hyperlink.

    3 Column CSS Layout with Header and Footer

    I am not a designer. But that should not stop me from trying when I come across a designing requirement. I helped a colleague of mine with a designing requirement where he needed to design a 3 Column Layout using CSS that had a header and footer. One of the main requirements was that the layout should automatically get adjusted (flow) to the contents. We took tips from loads of articles on the same topic and here’s what we came up with

    <!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>
    <
    title>3 Column CSS Layout with Header and Footer</title>
    <
    style type='text/css'>
    .header{
    position: relative;
    float: left;
    width: 100%;
    background-color: #356aa0
    }
    .container{
    position: relative;
    float: left;
    width: 100%;
    background-color: #cccccc
    }
    .left{
    position: relative;
    float: left;
    width: 20%;
    background-color: #a2b5cd
    }
    .center{
    position: relative;
    float: left;
    left: 1%;
    right:1%;
    width: 58%;
    background-color: #a2b5cd
    }
    .right{
    position: relative;
    float: right;
    width: 20%;
    background-color: #a2b5cd
    }
    .footer{
    position: relative;
    float: left;
    width: 100%;
    background-color: #356aa0
    }
    body {
    padding: 0px;
    margin: 2%;
    background-color: #e7e7de
    }
    </style>
    </
    head>
    <
    body>
    <
    div class="header">
    Header Text
    </div>
    <
    div class="container">
    <
    div class="left">
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left
    left left left left left left left left left left left left

    </div>
    <
    div class="center">
    center
    </div>
    <
    div class="right">
    right
    </div>
    </
    div>
    <
    div class="footer">
    Footer Text
    </div>
    </
    body>
    </
    html>



    OUTPUT

    image

    Suggestions are welcome!