Highlight a row in a table based on a search string using jQuery

I had recently posted on changing the border color when the user hovers over a table. A user mailed me back asking if it was possible to highlight only a cell based on a search string passed. Here's how to do so:

The trick is to use selectors http://docs.jquery.com/Selectors

<html xmlns="http://www.w3.org/1999/xhtml">

<
head >
<
title>Search and highlight Border Color on Hover</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>

<
script type="text/javascript">
$(document).ready(function() {
$(".someClass").hover(
function() {
$("td:contains('Row 1, Column 1')").css("border", "Solid Brown 1px");
},
function() {
$("td:contains('Row 1, Column 1')").css("border", "");
});
});
</script>
</
head>

<
body>
<
form id="form1" >
<
table id="tblOuter" class="someClass" style="width:50%">
<
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>
</
table>
</
form>
</
body>
</
html>

Live Demo

So when the user hovers over the table, only the cell with Row 1 Column 1 text gets highlighted. The text has been hardcoded here but can easily be replaced to accept the value from a textbox.

Change Table Border Color On Hover using jQuery

Here'a a very simple way to change the Table/Grid/GridView Border Color on Hover. This assumes that your control renders the <table> tag


<html xmlns="http://www.w3.org/1999/xhtml">


<head runat="server">


    <title>Border Color on Hover</title>


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


 


 <script type="text/javascript">


     $(document).ready(function() {


         $(".someClass").hover(


      function() {


         $(this).css({ "border": "Solid Brown 1px" });


      },


      function() {


          $(this).css({ "border": "" });


      });


     });


 </script>   


</head>


<body>


    <form id="form1" runat="server">                 


        <table id="tblOuter" class="someClass" style="width:50%">


        <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>


       </table>


    </form>


</body>


</html>


jQuery 1.3.2 Intellisense for Visual Studio 2008 now available

jQuery 1.3.2 intellisense documentation for Visual Studio 2008 is now available and can be downloaded from here

If you are new to jQuery intellisense in Visual Studio 2008, check one of my posts at dotnetcurry, Using jQuery with ASP.NET - A Beginner's Guide where I have covered it step by step.

Disable a Button if non numeric characters are entered

Here's a scenario. You have to accept only numeric characters from the user in a textbox. If the user types in anything other than a numeric character, then the submit button should be disabled.

To achieve this requirement we can use JavaScript and the OnKeyUp event as shown below:

Script


<head runat="server">


<title></title>


<script type="text/javascript">


function CallScript(sender, btn) {


var chkDigit = /^\d+$/;


if (chkDigit.test(sender.value)) {


document.getElementById(btn).disabled = false;


}


else {


document.getElementById(btn).disabled = true;


}


}


</script>




</head>


<body>


<form id="form1" runat="server">


<div>


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


<asp:Button ID="Button1" runat="server"


Text="Submit" Enabled="false" />


</div>


</form>


</body>


</html>




To register the OnKeyUp with the TextBox use the following code:

C#


protected void Page_Load(object sender, EventArgs e)


{


TextBox1.Attributes.Add("onKeyUp", "CallScript(this,'Button1')");


}






VB.NET


Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


TextBox1.Attributes.Add("onKeyUp", "CallScript(this,'Button1')")


End Sub




If you are using this script in a MasterPage, make sure to use Button1.ClientID

Note: Watch for the Copy and Paste scenarios where you will need to use the TextChangedEvent.

Putting (&) ampersand sign in a SiteMapNode

Have you tried adding an ampersand (&) in an ASP.NET SiteMapNode?

For eg: The following will not work


<siteMapNode url="~/Something.aspx?CatID=54" title="ASP.NET 2.0 & 3.5" description="" />




To add an ampersand sign in the sitemapnode, use either & amp;(without space) or & #38;(without space) as shown below:


<siteMapNode url="~/Something.aspx?ID=54" title="ASP.NET 2.0 &amp; 3.5" description="" />


How to do a Page PostBack With a Delay

Here's a simple way to delay a Page PostBack.

Add the following code in the Page_Load event:

C#


    protected void Page_Load(object sender, EventArgs e)


    {


        TimeSpan ts = new TimeSpan(0, 0, 0, 5);


        System.Threading.Thread.Sleep(ts);


    }




VB.NET


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


        Dim ts As New TimeSpan(0, 0, 0, 5)


        System.Threading.Thread.Sleep(ts)


    End Sub





Note: Avoid using this approach too much in a Production environment.

jQuery 1.3.2 released

jQuery 1.3.2 has been released. This release is a maintenance release with some significant changes to improve performance and behaviour.

Here are some important links:

Release Notes

jQuery 1.3.2 Regular

jQuery 1.3.2 Minified

Add OnKeyUp to an ASP.NET TextBox

Here's a simple technique to add OnKeyUp to an ASP.NET Textbox. In the Page_Load add the following code:

C#


    protected void Page_Load(object sender, EventArgs e)


    {


        TextBox1.Attributes.Add("onKeyUp", "CallScript(this)");


    }






VB.NET


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


        TextBox1.Attributes.Add("onKeyUp", "CallScript(this)")


    End Sub


Ask user before closing the browser - IE and Mozilla

If you would like to ask the user for confirmation before closing the browser , then here's how to do so. You can use this script on an ASP.NET page or a simple HTML page. The code has been tested on IE 7 and Firefox 3+


<head runat="server">


<title></title>


<script type="text/javascript">


window.onbeforeunload = function() {


if (window.event)


window.event.returnValue = 'Thank you for visiting us!';


else


return 'Thank you for visiting us!';


}


</script>


</head>

How to execute javascript onLoad only once in an ASP.NET page

If you are working on a ASP.NET Master/Content Page scenario and have declared a javascript onload, then the script gets executed every on every postback.

However if you would like to execute it only once during the first postback, then here's how to do so:
Copy this code in the <head> of your MasterPage



<script type="text/javascript">


function invokeMeMaster() {


var chkPostBack = '<%= Page.IsPostBack ? "true" : "false" %>';


if (chkPostBack == 'false') {


alert('Only the first time');


}

}



window.onload = function() { invokeMeMaster(); };


</script>



The code determines if there is a postback in Javascript and then executes code based on the result. Hence the alert popup is shown only once.

You can several other tips related to calling JavaScript in Master/Content Pages over here:

Calling JavaScript from ASP.NET Master Page and Content Pages - Part I

Calling JavaScript from ASP.NET Master Page and Content Pages - Part II

Access ASP.NET Master Page controls from Content Page

Mentioned here are two ways you can access MasterPage controls from Content Page

Approach 1

Go to the Content page (Default.aspx) and add the following line below the <Page> directive to register the MasterPage


<%@ MasterType VirtualPath="~/MasterPage.master" %>




Now in the code behind of ContentPage, access the MasterPage control in the following manner

C#


TextBox tb = (TextBox)Master.FindControl("txtMaster");


tb.Text = "Something";




VB.NET


        Dim tb As TextBox = CType(Master.FindControl("txtMaster"), TextBox)


        tb.Text = "Something"





Approach 2

Expose the Text property of the TextBox control in the MasterPage and use get set properties as shown below

C#


public string SomeText


{


    get


    {


        return txtMaster.Text;


    }


    set


    {


        txtMaster.Text = value;


    }


 


}





VB.NET


    Public Property SomeText() As String


        Get


            Return txtMaster.Text


        End Get


        Set(ByVal value As String)


            txtMaster.Text = value


        End Set


 


    End Property




Now accessing the Text property from the Content page is as simple as this line of code. Add the code in the codebehind of the MasterPage


Master.SomeText = "Something";


Ask For Confirmation Before Submitting Data in ASP.NET

Here's a simple way to ask the user for confirmation before submitting data:

C#

protected void Page_Load(object sender, EventArgs e)


{


    string myScript = @"<script type='text/javascript'>


    function askBeforeSubmit() {


    var msg = 'Are you sure?';


    return confirm(msg);


    }


    </script>";


    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MakeSure", myScript);


    form1.Attributes.Add("onsubmit", "return askBeforeSubmit();");


}





VB.NET

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        Dim myScript As String = "<script type='text/javascript'>" & ControlChars.CrLf & "    function askBeforeSubmit() {" & ControlChars.CrLf & "    var msg = 'Are you sure?';" & ControlChars.CrLf & "    return confirm(msg);" & ControlChars.CrLf & "    }" & ControlChars.CrLf & "    </script>"


        Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MakeSure", myScript)


        form1.Attributes.Add("onsubmit", "return askBeforeSubmit();")


 


    End Sub





You can also ask for confirmation without writing any code. Just use the OnClientClick event on the button as shown below:


<asp:Button ID="btnMaster" runat="server" Text="Button"


OnClientClick="return confirm('Are you sure?');"/>


How to Create an ASP.NET AJAX ModalPopUp Extender Dynamically

You may need to create a ModalPopUpExtender dynamically. Here's some code on how to do so:

Add the following markup in your page:


<body>


<form id="form1" runat="server">


<asp:ScriptManager ID="ScriptManager1" runat="server">


</asp:ScriptManager>


<div>


<asp:Panel ID="Panel1" runat="server">


    <asp:Button ID="Button1" runat="server"


    Text="CreateModal" OnClick="Button1_Click" />


</asp:Panel>


<asp:Panel ID="ModalPanel" runat="server"


    Style="display: none"


    BackColor="Gray">


    Dynamic ModalPopup!


    <asp:Button ID="btnCancel" runat="server" Text="Close Me" />


</asp:Panel>


</div>


</form>


</body>




Then in the code behind, add the following code. On clicking the Button, we have added code to create another button dynamically which contains functionality to show and hide a ModalPopUp

C#


protected void Button1_Click(object sender, EventArgs e)


{


    Button btnNew = new Button();


    btnNew.ID = "Button2";


    btnNew.Text = "Click Me to Show PopUp";


 


    AjaxControlToolkit.ModalPopupExtender modalPop =


        new AjaxControlToolkit.ModalPopupExtender();


    modalPop.ID = "popUp";


    modalPop.PopupControlID = "ModalPanel";


    modalPop.TargetControlID = "Button2";


    modalPop.DropShadow = true;


    modalPop.CancelControlID = "btnCancel";


 


    this.Panel1.Controls.Add(modalPop);


    this.Panel1.Controls.Add(btnNew);


 


}




VB.NET


Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)


        Dim btnNew As New Button()


        btnNew.ID = "Button2"


        btnNew.Text = "Click Me to Show PopUp"


 


        Dim modalPop As New AjaxControlToolkit.ModalPopupExtender()


        modalPop.ID = "popUp"


        modalPop.PopupControlID = "ModalPanel"


        modalPop.TargetControlID = "Button2"


        modalPop.DropShadow = True


        modalPop.CancelControlID = "btnCancel"


 


        Me.Panel1.Controls.Add(modalPop)


        Me.Panel1.Controls.Add(btnNew)


 


    End Sub


How to Display Last Login Date for a User in ASP.NET

If you are using Forms Authentication and want to find the last login date of a registered user, here's how to do so. In the Login_Authenticate event, use the following code just before authentication the user:

C#


protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)


{


MembershipUser mu = Membership.GetUser(Login1.UserName);


DateTime dt = mu.LastLoginDate;


Session["lastlogindt"] = dt;



// Then authenticate the user here (e.Authenticate = true)


}




VB.NET


Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As AuthenticateEventArgs)


Dim mu As MembershipUser = Membership.GetUser(Login1.UserName)


Dim dt As DateTime = mu.LastLoginDate


Session("lastlogindt") = dt



' Then authenticate the user here


End Sub


List Count of Duplicate Names in LINQ

If you have a Generic list with Employee Information and want to take a count of the Employees having the same name, here's how to do so:

C#

    protected void Page_Load(object sender, EventArgs e)


    {


    List<Employee> empList = new List<Employee>();


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


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


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


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


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


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


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


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


 


    var dup = empList


        .GroupBy(x => new { x.FName })


        .Select(group => new { Name = group.Key, Count = group.Count() })


        .OrderByDescending(x => x.Count);


        foreach (var x in dup)


        {


            Response.Write(x.Count + " " + x.Name);


        }


    }


 


    class Employee


    {


        public int ID { get; set; }


        public string FName { get; set; }


        public int Age { get; set; }


        public char Sex { get; set; }


    }




VB.NET


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


        Dim empList As New List(Of Employee)()


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


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


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


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


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


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


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


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


 


        Dim dup = empList _


        .GroupBy(Function(x) New With {Key x.FName}) _


        .Select(Function(group) New With {Key .Name = group.Key, Key .Count = group.Count()}) _


        .OrderByDescending(Function(x) x.Count)


        For Each x In dup


            ' Use x.count and x.Name


        Next x


    End Sub


 


    Friend 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


    End Class


End Class


How do you check if SQLDataSource returns empty data

A user asked me a simple way to determine if the SQLDataSource returns empty data.

Here's a simple way to do so: Use the OnSelected event of the SQLDataSource


<asp:SqlDataSource ID="SqlDataSource1" runat="server"


ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"


SelectCommand="SELECT [CustomerID], [CompanyName], [ContactName],


[ContactTitle], [Address] FROM [Customers]"


onselected="SqlDataSource1_Selected">


</asp:SqlDataSource>




C#


protected void SqlDataSource1_Selected(object sender, SqlDataSourceStatusEventArgs e)


{


if (e.AffectedRows < 1)


{


// perform action


}


}




VB.NET


Protected Sub SqlDataSource1_Selected(ByVal sender As Object, ByVal e As SqlDataSourceStatusEventArgs)


If e.AffectedRows < 1 Then


' perform action


End If


End Sub



Note: As pointed out by a reader, this tip will not work if SQLDataSource caching is enabled.

GroupBy Multiple Values in LINQ

Here's a simple example to show you how to GroupBy Multiple Values using LINQ. In this example, I am grouping by Age and Sex to find the count of people who have the same age and sex

public partial classLINQ: System.Web.UI.Page
{
protected void Page_Load(objectsender, EventArgs e)
{
List<Employee> empList = newList<Employee>();
empList.Add(newEmployee(){ID = 1, FName = "John", Age = 23, Sex = 'M'});
empList.Add(newEmployee(){ID = 2, FName = "Mary", Age = 25, Sex = 'F' });
empList.Add(newEmployee(){ID = 3, FName = "Amber", Age = 23, Sex = 'M'});
empList.Add(newEmployee(){ID = 4, FName = "Kathy", Age = 25, Sex = 'M'});
empList.Add(newEmployee(){ID = 5, FName = "Lena", Age = 27, Sex = 'F' });
empList.Add(newEmployee(){ID = 6, FName = "Bill", Age = 28, Sex = 'M'});
empList.Add(newEmployee(){ID = 7, FName = "Celina", Age = 27, Sex = 'F' });
empList.Add(newEmployee(){ID = 8, FName = "John", Age = 28, Sex = 'M'});

var sums = empList
.GroupBy(x => new{ x.Age, x.Sex })
.Select(group => new{ Peo = group.Key, Count = group.Count() });

foreach (var employee insums)
{
Response.Write(employee.Count + ": "+ employee.Peo);
}

}
}

classEmployee
{
public int ID { get; set; }
public stringFName { get; set; }
public int Age { get; set; }
public charSex { get; set; }
}

You can also check out similar LINQ Tutorials over here

FREE Ebook and E-Learning: Understanding Microsoft Virtualization Solutions

The following e-book is available free of cost:

Understanding Microsoft Virtualization Solutions
By Mitch Tulloch with the Microsoft Virtualization Teams

As given on the site
"This guide will teach you about the benefits of the latest virtualization technologies and how to plan, implement, and manage virtual infrastructure solutions. The technologies covered include: Windows Server 2008 Hyper-V, System Center Virtual Machine Manager 2009, Microsoft Application Virtualization 4.5, Microsoft Enterprise Desktop Virtualization, and Microsoft Virtual Desktop Infrastructure"


Download link

On top of this, you can also get the "Exploring Microsoft Virtualization Technologies" E-Learning collection Free of Cost.

Get the free e-learning over here: Collection 6333: Exploring Microsoft Virtualization Technologies

Implementing Paging in a Generic List using LINQ

It's quite common of users to bind their Generic List to an ASP.NET control. However if the list is huge, you may need to implement Paging functionality. Here's a simple way to do implement Paging functionality using LINQ

C#

using System;


using System.Collections.Generic;


using System.Linq;


using System.Web;


using System.Web.UI;


using System.Web.UI.WebControls;


 


public partial class LINQ : System.Web.UI.Page


{


    protected void Page_Load(object sender, EventArgs e)


    {


        List<Employee> empList = new List<Employee>();


        empList.Add(new Employee() { ID = 1, FName = "John",  DOB = DateTime.Parse("12/11/1971")});


        empList.Add(new Employee() { ID = 2, FName = "Mary",  DOB = DateTime.Parse("01/17/1961")});


        empList.Add(new Employee() { ID = 3, FName = "Amber", DOB = DateTime.Parse("12/23/1971")});


        empList.Add(new Employee() { ID = 4, FName = "Kathy", DOB = DateTime.Parse("11/15/1976")});


        empList.Add(new Employee() { ID = 5, FName = "Lena",  DOB = DateTime.Parse("05/11/1978")});


 


        var records = from emp in empList


                      select emp;


        var pgNo = 1;


        var pgRec = 2;


        records = records.Skip((pgNo - 1) * pgRec).Take(pgRec);


 


        foreach (var r in records)


        {


            Console.WriteLine(r.FName);


        }


 


    }


 


    class Employee


    {


        public int ID { get; set; }


        public string FName { get; set; }


        public DateTime DOB { get; set; }


    }


 


}





VB.NET

Imports System


Imports System.Collections.Generic


Imports System.Linq


Imports System.Web


Imports System.Web.UI


Imports System.Web.UI.WebControls


 


Partial Public Class LINQ


    Inherits System.Web.UI.Page


    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)


        Dim empList As New List(Of Employee)()


        empList.Add(New Employee() With {.ID = 1, .FName = "John", .DOB = DateTime.Parse("12/11/1971")})


        empList.Add(New Employee() With {.ID = 2, .FName = "Mary", .DOB = DateTime.Parse("01/17/1961")})


        empList.Add(New Employee() With {.ID = 3, .FName = "Amber", .DOB = DateTime.Parse("12/23/1971")})


        empList.Add(New Employee() With {.ID = 4, .FName = "Kathy", .DOB = DateTime.Parse("11/15/1976")})


        empList.Add(New Employee() With {.ID = 5, .FName = "Lena", .DOB = DateTime.Parse("05/11/1978")})


 


        Dim records = _


         From emp In empList _


         Select emp


        Dim pgNo = 1


        Dim pgRec = 2


        records = records.Skip((pgNo - 1) * pgRec).Take(pgRec)


 


        For Each r In records


            Console.WriteLine(r.FName)


        Next r


 


    End Sub


 


    Private 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 privateDOB As DateTime


        Public Property DOB() As DateTime


            Get


                Return privateDOB


            End Get


            Set(ByVal value As DateTime)


                privateDOB = value


            End Set


        End Property


    End Class


 


End Class




Observe how we have used the Skip and Take function on the List.