jQuery and ASP.NET

September 30, 2009

Check Uncheck all CheckBoxes in an ASP.NET GridView kept in an Update Panel using jQuery

0 comments


In one of my previous posts, I had shown how to Check Uncheck all CheckBoxes in an ASP.NET GridView using jQuery

Users mailed back telling me that the example did not work in an UpdatePanel. I suspect the error they got was this:

“Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled”

The reason why this error occurs has been given very clearly over here

Here’s how to solve it:

1. Wrap the GridView and the Button in an Update Panel

2. Add a Literal control to the Page

<asp:Literal ID="lblResults" runat="server" Text=""></asp:Literal>

3. Instead of using Response.Write(), write the results to this Literal control

C#

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)
{
lblResults.Text += "Employee Id: " +
GridView1.DataKeys[row.RowIndex].Value
+ " Name: " + row.Cells[2].Text + "<br/>";
}
}
}

VB.NET

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
lblResults.Text &= "Employee Id: " & _
GridView1.DataKeys(row.RowIndex).Value & " Name: " & _
row.Cells(2).Text & "<br/>"
End If
Next
row
End Sub

September 29, 2009

Web Platform Installer 2.0

0 comments


As given on the site “The Microsoft Web Platform Installer 2.0 (Web PI) is a free tool that makes getting the latest components of the Microsoft Web Platform, including Internet Information Services (IIS), SQL Server Express, .NET Framework and Visual Web Developer easy.”

Here are some highlights of this new release:

- installing popular community ASP.NET and PHP applications

- localization into 9 languages,

- expansion to include more scenarios around Media, Dev Tools, and Enterprise.

So go ahead and check out this tool.

You can download the Web Platform Installer RTW over here

September 28, 2009

Handle Uneven Spaces in a String using C# or VB.NET

0 comments


I was facing a requirement where the words in a string that was sent to an application had uneven spaces in it. The client wanted the string spacing to be readjusted to allow just one space between two words. Here’s how I solved it using Regex:


Add a reference to System.Text.RegularExpressions


C#

string str = "This string   has    odd number of spaces";

Console.WriteLine("Before adjusting spaces : " + str);

string newStr = Regex.Replace(str, @"\s+", " ");

Console.WriteLine("After adjusting spaces : " + newStr);

Console.ReadLine();

VB.NET

Dim str As String = "This string   has    odd number of spaces"

Console.WriteLine("Before adjusting spaces : " & str)

Dim newStr As String = Regex.Replace(str, "\s+", " ")

Console.WriteLine("After adjusting spaces : " & newStr)

Console.ReadLine()

OUTPUT


image

September 27, 2009

Microsoft WebSite Spark and Web Application ToolKits

0 comments


Microsoft recently announced an amazing initiative for small time web developers and companies. It’s called WebsiteSpark. This is a program designed to jumpstart Web development for individuals or small companies who make a living on the Web. The program is free to join and runs for three years with no cost obligations other than a $100 program fee, payable on exit. Get more details over here

Microsoft has also launched a number of Web Application Toolkits to the Web. Web Application Toolkits are designed to enable Web Developers to simply extend their web application capabilities by providing them with a packaged set of running samples, templates and documentation.

Here are the List of Web Application Toolkits:

Web Application Toolkit for REST Services

Web Application Toolkit for Mobile Web Applications

Web Application Toolkit for Template-Driven Email

Web Application Toolkit for Making your Website Social

Web Application Toolkit for Bing Search

Web Application Toolkit for IE8

Web Application Toolkit for FAQs

September 26, 2009

C# Coding Standards, Design Guidelines and Tools

3 comments


I have seen a lot of people asking for a C# Coding Standard and Design Guide. Here are some documents and tools that I refer to:

IDesign C# Coding Standard

C# Coding Standards document

Encodo C# Handbook

Design Guidelines for Developing Class Libraries

Internal Coding Guidelines

Tools - StyleCop

September 25, 2009

Using jQuery to Ensure TextBoxes have Data before Enabling the Submit Button

1 comments


Here’s a simple way to prevent the user from submitting a form by disabling the submit button until all of the text boxes contain a value.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Ensure Text Boxes Have Data</title>
<
script type="text/javascript" language="javascript"
src="http://code.jquery.com/jquery-latest.js"></script>
<
script type="text/javascript" language="javascript">
$(document).ready(function() {
// Set the focus on the fist text box
$("input[type=text]:first").focus();

controlButton();
$("input[type=text]").keyup(function() {
controlButton();
});

function controlButton() {
var textEntered = true;
$("input[type=text]").each(function() {
if (textEntered && $(this).val().length == 0) {
textEntered = false;
}
});

if (textEntered) {
$("#btnSubmit").attr("disabled", "");
} else {
$("#btnSubmit").attr("disabled", "disabled");
}
}
});
</script>
</
head>
<
body>
<
form>
<
input id="Text1" type="text" /><br />
<
input id="Text2" type="text" /><br />
<
input id="Text3" type="text" /><br />
<
input id="btnSubmit" type="submit" value="Submit" />
</
form>
</
body>
</
html>


The user will be allowed to submit the form if they have entered data into each text box:

clip_image002

However if they leave just one field blank, the Submit button will be disabled:

clip_image004

September 24, 2009

Make Sure atleast One CheckBox is checked before submitting the Form - jQuery

0 comments


Here’s a simple way to keep a required checkbox on the form and prevent the user from submitting a form, if one of the checkboxes is not checked:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Make Sure Atleast One CheckBox is Checked</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('input[id$=btnSubmit]').click(function(e) {
var checked = $(':checkbox:checked').length;
if (checked == 0) {
alert('Atleast One CheckBox Should Be Selected');
e.preventDefault();
}
});
});
</script>
</
head>
<
body>
<
input id="cb1" type="checkbox" value="1"/> Option One
<input id="cb2" type="checkbox" value="2"/> Option Two
<input id="cb3" type="checkbox" value="3"/> Option Three
<input id="btnSubmit" type="submit" value="Submit" />

</
body>
</
html>


To do this with ASP.NET controls in an ASP.NET application, the jQuery code remains the same. Just replace the following html controls with server controls:

<body>
<
form id="form1" runat="server">
<
div>
<
asp:CheckBox ID="cb1" runat="server" Text="Option One" /><br />
<
asp:CheckBox ID="cb2" runat="server" Text="Option Two" /><br />
<
asp:CheckBox ID="cb3" runat="server" Text="Option Three" /><br />
<
asp:Button ID="btnSubmit" runat="server" Text="Submit" />

</
div>
</
form>
</
body>

When the user tries to submit the form without checking any of the checkboxes, he/she gets an alert as shown below:

image

See a Live Demo

September 23, 2009

Count Words and Characters in a String using C# or VB.NET

0 comments


A user recently asked me a question on how to use Regular Expressions to count words and characters in a string. Here’s how:

First add a reference to ‘System.Text.RegularExpressions’

C#

// Count words
MatchCollection wordColl =
Regex.Matches(strOriginal, @"[\S]+");
Console.WriteLine(wordColl.Count.ToString());
// Count characters. White space is treated as a character
MatchCollection charColl = Regex.Matches(strOriginal, @".");
Console.WriteLine(charColl.Count.ToString());

VB.NET

' Count words
Dim wordColl As MatchCollection = Regex.Matches(strOriginal, "[\S]+")
Console.WriteLine(wordColl.Count.ToString())
' Count characters. White space is treated as a character
Dim charColl As MatchCollection = Regex.Matches(strOriginal, ".")
Console.WriteLine(charColl.Count.ToString())

Here the strOriginal is your string.

I covered some frequently used string operations in my articles on www.dotnetcurry.com over here:

30 Common String Operations in C# and VB.NET – Part I

30 Common String Operations in C# and VB.NET – Part II

September 22, 2009

Retrieve the Value of an ASP.NET CheckBox in jQuery

0 comments


In this post, let us see how to retrieve the text of an ASP.NET CheckBox using jQuery

Declare an ASP.NET CheckBox control as shown below:

<asp:CheckBox ID="cb1" runat="server" Text="Option One" />

Now a lot of users try to retrieve the text of this checkbox in the following manner:

alert($("#Checkbox1").val());

However this code does not work for an ASP.NET Checkbox control. Let us see why. This control renders to the following HTML

<input id="Checkbox2" type="checkbox" name="cb1" />
<
label for="cb1">Option One</label>

If you observe, a label control gets created which holds the text for the CheckBox.

In order to retrieve the text of this checkbox, change the jQuery code to:

alert($("input:checkbox[id$=cb1]").next().text());

and now the code would alert ‘Option One’

Note: The same code could have also been written as alert($("#cb1").next().text()). However the code given above works in the case of a MasterPage too. I prefer the above one!

September 21, 2009

Synchronize Scrolling of Two TextArea or Multiline ASP.NET TextBoxes using jQuery

2 comments


The technique shown below synchronizes the scrolling of TextBox (tb2) with TextBox (tb1). As the user scrolls through the contents of tb1, the contents of tb2 is automatically scrolled to keep up with the display of tb1. The code shown here fits a requirement where two versions of the same document are to be compared with each other and the user need not have to explicitly scroll through both the textboxes to compare them.

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Sync two Multiline TextBoxes</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$('textarea[id$=tb1]').scroll(function() {
$('textarea[id$=tb2]')
.scrollTop($('textarea[id$=tb1]').scrollTop());
});
});
</script>
</
head>
<
body>
<
textarea id="tb1" cols="20" rows="2">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</textarea>
<
textarea id="tb2" cols="20" rows="2">
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
</textarea>
</
body>
</
html>

Note: You can also access the contents of the textarea using $(‘#tb1’) instead of $('textarea[id$=tb1]').

ASP.NET Multiline TextBoxes

The same code also works for two ASP.NET Multiline Textboxes

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Sync two Multiline TextBoxes</title>

<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('textarea[id$=tb1]').scroll(function() {
$('textarea[id$=tb2]')
.scrollTop($('textarea[id$=tb1]').scrollTop());
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="tb1" runat="server" TextMode="MultiLine"
Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum" />
<
asp:TextBox ID="tb2" runat="server" TextMode="MultiLine"
Text="Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum" />
<
br />
</
div>
</
form>
</
body>
</
html>

See a Live Demo

September 20, 2009

Convert PPT to Silverlight

0 comments


I have seen this question come up too often – How to convert PPT to Silverlight.? On researching, here are some tools I found:

Save to Silverlight – Powerpoint 2007 Add-in that converts your pptx file into a Silverlight xap file.

Convexion – A promising brand new PowerPoint 2007 plug-in from ElectricRain that enables users to publish their PowerPoint slideshows to the Microsoft Silverlight and WPF formats

PowerPoint to Silverlight Convertor – Free Tool that Converts Static slides.

Another approach is to convert your Powerpoint to XPS and use a XPS Viewer in Silverlight to view the files

September 19, 2009

Clone the Value of a TextBox as the User Types in it using jQuery

0 comments


I recently saw a question on the forums where a user wanted to clone the value of a textbox contents into another, as he typed in it. Here’s how to achieve this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Clone the Value of a TextBox as the User Types in it</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#tb1").keyup(function() {
var txtClone = $(this).val();
$("#tb2").val(txtClone);
});
});
</script>
</
head>
<
body>
<
input id="tb1" type="text" />
<
input id="tb2" type="text" />
</
body>
</
html>



To do it an ASP.NET Page

<html xmlns="http://www.w3.org/1999/xhtml">
<
head id="Head1" runat="server">
<
title>Clone the Value of a TextBox as the User Types in it</title>
<
script type='text/javascript'
src='http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js'>
</
script>

<
script type="text/javascript">
$(function() {
$('input[id$=tb1]').keyup(function() {
var txtClone = $(this).val();
$('input[id$=tb2]').val(txtClone);
});
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="tb1" runat="server" /><br />
<
asp:TextBox ID="tb2" runat="server" />
</
div>
</
form>
</
body>
</
html>

Observe how I am using ('input[id$=tb1]' in an ASP.NET page. Using this technique makes it easy to find a control in a MasterPage scenario.

See a Live Demo

September 18, 2009

Using Microsoft's CDN Service with jQuery

0 comments


Microsoft yesterday announced it has created a new Microsoft Ajax CDN (Content Delivery Network) that provides caching support for Ajax libraries. The CDN contains copies of data, placed at various locations, to maximize bandwidth. For example if your website is hosted in Australia, but you’re a visitor from the United Kingdom, then the data must travel between those two points. A CDN allows the visitor in the UK to download the files near themselves as opposed to the server in Australia. This provides a real boost to a websites performance.

You can get a full listing of the JavaScript libraries (and associated URLs) we already have loaded in our CDN cache here. To use this with jQuery, simply add the full path to the CDN service:

<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"
type="text/javascript"></script>

Here’s a quick example of how to use this in Visual Studio.

<!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>Using Microsoft's CDN Service with jQuery</title>
<
script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.min.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).ready(function() {
$("div").one("click", function() {
var index = $("div").index(this);
$(this).css({ borderStyle: "inset", cursor: "auto" });
});
});
</script>
<
style type="text/css">
div
{
width: 60px;
height: 60px;
margin: 5px;
float: left;
background: green;
border: 10px outset;
cursor: pointer;
}
p
{
color: red;
margin: 0;
clear: left;
}
</style>
</
head>
<
body>
<
div></div>
<
div></div>
<
div></div>
<
div></div>
<
div></div>
<
p>Click a green square...</p>
</
body>
</
html>

If you copy the example above and run it locally, you’ll be using a copy of jQuery’s library that is closest to your current location.

September 17, 2009

Bind Multiple Controls to a Single Event in jQuery

5 comments


In this sample, we will see how to bind Multiple Controls to a single event. We will bind 3 button controls (Button A, C and E) to a single click event. This example also demonstrates how to create an array of controls and loop through them. Here’s how:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Multiple Elements Single Event</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
var btns = $('#btn1,#btn3,#btn5');
$.each(btns, function() {
$(this).click(function() {
alert(this.id);
});
});
});
</script>
</
head>
<
body>
<
input id="btn1" type="button" value="Button A" />
<
input id="btn2" type="button" value="Button B" />
<
input id="btn3" type="button" value="Button C" />
<
input id="btn4" type="button" value="Button D" />
<
input id="btn5" type="button" value="Button E" />
<
input id="btn6" type="button" value="Button F" />
</
body>
</
html>
See a Live Demo here

September 16, 2009

Set the Line Color Between Rows in an ASP.NET GridView

0 comments


Have you wondered how to set the color between two rows in an ASP.NET GridView. The GridView control does not provide a direct attribute for setting a color to the lines between two rows. But here’s how to do it using CSS:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Change Color of Lines</title>
<
style type="text/css">
.gridLines td
{
border-bottom: 1px solid Gray;
}
</style>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
GridLines="Horizontal" CssClass="gridLines" DataKeyNames="ID" >
<
Columns>
...
</Columns>
</
asp:GridView>
</
div>
</
form>
</
body>
</
html>

OUTPUT

image

September 15, 2009

ASP.NET AJAX 4.0 Preview 5

0 comments


Microsoft recently released ASP.NET AJAX 4.0 Preview 5.

The highlights of this release are

- Support for UpdatePanels with ASP.NET 3.5 SP1 or ASP.NET 4.0. There was a compatibility issue with the UpdatePanel in the Preview 4 version.

- Dynamic and recursive templates

- Binding Converters

You also get a Visual Studio project with sample code demonstrating the features of ASP.NET AJAX 4.0 Preview 5.Here are some useful links related to this release:

ASP.NET AJAX 4.0 Preview 5 Download Link

ASP.NET Ajax Preview 5 and UpdatePanel

ASP.NET AJAX 4.0 Preview 5 available

Microsoft Ajax 4 Preview 5: The DataView Control

September 14, 2009

Programmatically Load a GridView Row in Edit Mode

2 comments


A user in asp.net forums asked a question about loading a GridView Row programmatically in EditMode. It’s quite simple actually. You just have to set the EditIndex to the row number that needs to be edited and bind the GridView with the datasource. Here’s an example:

C#

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Employee emp = new Employee();
listEmp = emp.GetEmployees();
// Add Row in Edit Mode
GridView1.EditIndex = 3;
// Bind GridView to its Source
this.GridView1.DataSource = listEmp;
this.GridView1.DataBind();
}
}

VB.NET

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()
' Add Row in Edit Mode
GridView1.EditIndex = 3
' Bind GridView to its Source
Me.GridView1.DataSource = listEmp
Me.GridView1.DataBind()
End If
End Sub

OUTPUT

image

Just remember the EditIndex to RowNumber – 1. So to load Row 4 in EditMode, set the EditIndex to 3. You may also want to check the number of rows before you set the EditMode to avoid Errors.

September 13, 2009

Difference Between ASP.NET WebForms and ASP.NET MVC

7 comments


One of the frequently asked questions about ASP.NET MVC is that how is different from ASP.NET WebForms. Is ASP.NET MVC a replacement for WebForms.

The answer is No. ASP.NET MVC, is not a replacement for WebForms. Both ASP.NET MVC and ASP.NET WebForms are built on top of the Core ASP.NET Framework. In fact a lot of features we use in ASP.NET such as Roles, Membership, Authentication and a lot of namespaces, classes and interfaces can be used in an ASP.NET MVC application

Here are some points that I wrote in an article for www.dotnetcurry.com that differentiate ASP.NET WebForms from ASP.NET MVC:

ASP.NET WebForms

ASP.NET MVC

Uses the ‘Page Controller’ pattern. Each page has a code-behind class that acts as a controller and is responsible for rendering the layout.Uses the ‘Front Controller’ pattern. There is a single central controller for all pages to process web application requests and facilitates a rich routing architecture
Uses an architecture that combines the Controller (code behind) and the View (.aspx). Thus the Controller has a dependency on the View. Due to this, testing and maintainability becomes an issue.ASP.NET MVC enforces a "separation of concerns". The Model does not know anything about the View. The View does not know there’s a Controller. This makes MVC applications easier to test and maintain
The View is called before the Controller.Controller renders View based on actions as a result of the User Interactions on the UI.
At its core, you ‘cannot’ test your controller without instantiating a View. There are ways to get around it using tools.At its core, ASP.NET MVC was designed to make test-driven development easier. You ‘can’ test your Controller without instantiating a View and carry out unit-tests without having to run the controllers in an ASP.NET process.
WebForms manage state by using view state and server-based controls.ASP.NET MVC does not maintain state information by using view state
WebForms supports an event-driven programming style that is like Windows applications and is abstracted from the user. The State management is made transparent by using sessions, viewstate etc. In the process, the HTML output is not clean making it difficult to manage later. The ViewState also increases your page size.In ASP.NET MVC, the output is clean and you have full control over the rendered HTML. The orientation is towards building standard compliant pages and provides full control over the behavior of an application.
Deep understanding of HTML, CSS and JavaScript is not required to a large extent since the WebForm model abstracts a lot of these details and provides automatic plumbing. While abstracting details to provide ease of use, sometimes a solution is overcomplicated, than it needs to be.A thorough understanding of how HTML, CSS and JavaScript work together is required. The advantage is you can do a lot of jQuery and AJAX stuff in an efficient and simple manner than you would do in an ASP.NET application.
WebForms can drastically reduce time while building up intranet and internet applications that use a lot of controls (drag and drop model). Although this is true for development, a lot of time is spent later to code around limitations.You lose the 'drag and drop' quick model of building your web applications. The focus is on control over the application behavior and test-driven development. The model is extensible and you do not have to spend time working around limitations.
Relatively simple to learn and pickup. Works very well for developers who initially have trouble with the HTTP/HTML model and are coming from a similar WinForms oriented event model.There is a learning curve to understand the why, when and how of ASP.NET MVC.
Lesser amount of code is required to build webapps since a lot of components are integrated and provided out of the box. You can also use a lot of data controls provided out of the box that rely on ViewState.Since the application tasks are separated into different components, amount of code required is more. Since ASP.NET MVC does not use ViewState, you cannot use Data controls like GridView, Repeater.
Works very well for small teams where focus is on rapid application developmentWorks well for large projects where focus in on testability and maintainability

I hope devcurry.com viewers will find this table useful. The entire article can be read over here ASP.NET MVC - Some Frequently Asked Questions

September 12, 2009

Access Values from All or Selected Textboxes using jQuery

0 comments


I have seen a lot of users asking an easy and effective way to access values from all TextBoxes using jQuery. This post demonstrates that. I added a couple of extra requirements:

- The selected values should be listed separately on each line with minimal efforts.

- Empty Textboxes should be ignored.

Here’s the code:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Access Values from All or Selected Textboxes</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("#btnAll").click(function(e) {
$("p").text('').append($("input[type=text]").map(function() {
return $(this).val() || null;
}).get().join("<br/> "));
});

$("#btnSel").click(function(e) {
$("p").text('').append($("input.selected").map(function() {
return $(this).val() || null;
}).get().join("<br/> "));
});
});
</script>
</
head>
<
body>
<
input id="tb1" type="text" /><br />
<
input id="tb2" type="text" /><br />
<
input id="tb3" type="text" /><br />
<
input id="tb4" type="text" class="selected" /><br />
<
input id="tb5" type="text" /><br />
<
input id="tb6" type="text" class="selected"/><br />
<
input id="btnAll" type="button" value="Select All" />
<
input id="btnSel" type="button" value="Select Some" /><br />
<
p></p>

</
body>
</
html>

As you can observe, the code is triggered on Button Clicks. The first piece of code is invoked when the user clicks on ‘btnAll’. The code selects the value of all textboxes using the Traversing/Map function. Only the textboxes with some text in it are displayed. This is done using the $(this).val() || null; statement

Similarly on the click of ‘btnSel’, those textboxes which have class='”selected” are displayed.

image

You can see a Live Demo

September 11, 2009

How to Bind An Enum Name and Value to an ASP.NET DropDownList

2 comments


I had recently written a blog post on How to Bind an ASP.NET DropDownList to an Enumeration with two lines of code. A devcurry reader mailed back asking if it was possible to bind an Enumeration Name and Value to the DropDownList. Here’s how:

<asp:DropDownList ID="DropDownList1" runat="server">
</
asp:DropDownList>

C#

enum Speed
{
Low = 1,
Medium = 2,
High = 3
}
protected void Page_Load(object sender, EventArgs e)
{
Hashtable htSpeed = BindEnum(typeof(Speed));
DropDownList1.DataSource = htSpeed;
DropDownList1.DataValueField = "key";
DropDownList1.DataTextField = "value";
DropDownList1.DataBind();
}
protected Hashtable BindEnum(Type speedEnum)
{
string[] enumNm = Enum.GetNames(speedEnum);
int[] enumVal = (int[])Enum.GetValues(speedEnum);

Hashtable htSpeed = new Hashtable();
for (int cnt = 0; cnt < enumVal.Length; cnt++)
{
htSpeed.Add(enumVal.GetValue(cnt), enumNm[cnt]);
}
return htSpeed;
}

VB.NET

    Friend Enum Speed
Low = 1
Medium = 2
High = 3
End Enum

Protected Sub
Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Dim htSpeed As Hashtable = BindEnum(GetType(Speed))
DropDownList1.DataSource = htSpeed
DropDownList1.DataValueField = "key"
DropDownList1.DataTextField = "value"
DropDownList1.DataBind()
End Sub

Protected Function
BindEnum(ByVal speedEnum As Type) As Hashtable
Dim enumNm() As String = System.Enum.GetNames(speedEnum)
Dim enumVal() As Integer = _
                  CType(System.Enum.GetValues(speedEnum), Integer())

Dim htSpeed As New Hashtable()
For cnt As Integer = 0 To enumVal.Length - 1
htSpeed.Add(enumVal.GetValue(cnt), enumNm(cnt))
Next cnt
Return htSpeed
End Function


Note 1: You need not have to explicitly create a HashTable and then bind it to a DropDownList,

as shown in this example. Instead, you can also directly (quick and dirty) use:

DropDownList1.Items.Add(new ListItem(string text, string value));

I although prefer it the HashTable way since I can refer it at multiple places and it also looks neat to keep stuff seperate in your code!

Note 2: If you want the DropDownList to be sorted based on the value, just reverse the loop.

September 10, 2009

Create a Complete PC Backup and Restore in Vista

0 comments


A colleague of mine recently lost a big chunk of data due to a PC Malfunction. He had a Windows Vista Business Edition but never knew about the Windows Complete PC Backup and Restore tool! This post is to make my blog viewers aware of this tool and help you prepare for such malfunctions.

If you are running a Windows Vista Enterprise, Ultimate, and Business edition, then you have a very cool back up tool called Windows Complete PC Backup and Restore. In my opinion, this is the most useful tool in Vista for disaster recovery in case of a Hardware failure or malfunctions. This tool takes a back up of your entire PC environment, including the operating system, your programs, user settings and data.

Open Control Panel > BackUp and Restore Center >

image

Click on the ‘Back up Computer’ button > and click on ‘Continue’ in the User Access Control (UAC) prompt.

After searching for the BackUp Devices on your computer, Windows Vista comes up with the following screen

image

Choose the location where you want to save the backup – On a Hard Disk or on DVD’s.

The screen above clearly shows that there isn’t enough free space available on Data (D): to save the backup. In order to find out the approximate amount of disk space required for the backup, click Next

Select the disks you want to include in the back up. I have selected both C: and D:

image

Click on Next again. A screen similar to the one shown below displays the amount of space required for this back up i.e. approximately 257 GB or more, in my case.

image

Once you have arranged a disk with sufficient space, the last step is to click on ‘Start backup’ to start the backup process.

Note: Assuming you have already taken a complete backup using this tool, the next time you run this tool, only the differences will be saved.

Remember you need to run this tool before you run into a tight spot :-). It is a preparation tool!

Well this tool does make backup’s and restores a breeze. The not so breezy part is to arrange for a USB disk with 257 GB free space!!

September 9, 2009

Automatically Insert Double Quotes in your HTML Attributes in Visual Studio

0 comments


One thing that annoys me is unnecessary typing while hand coding HTML. Thankfully there’s an option inside Visual Studio that will automatically insert double quotes when you’re working with the HTML markup screen. Here’s how to turn this option on.

Open Visual Studio 2008 > Go to Tools > Options > Text Editor > HTML > Format

Under the Automatic formatting options, select Insert attribute value quotes when typing:

clip_image002

So now when you type an HTML attribute inside an element For eg: <input id= the double quotes get inserted for you automatically resulting in <input id=""

For me this is a real time saver.

September 8, 2009

Set Focus to the First TextBox on a Page using jQuery

6 comments


While browsing the asp.net forums, I came across a question where a user wanted to set focus to the first textbox in a Page. The condition here was the TextBox had to be enabled. Here’s how to do so:

HTML Page

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Select the First Enabled TextBox on the Form</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("input[type='text']:enabled:first").focus();
});
</script>
</
head>
<
body>
<
input id="Text1" type="text" disabled="disabled"/><br />
<
input id="Text2" type="text" disabled="disabled"/><br />
<
input id="Text3" type="text" /><br />
<
input id="Text4" type="text" /><br />
<
input id="Text5" type="text" />
</
body>
</
html>

ASP.NET Page

<html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Select the First TextBox on the Form</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(function() {
$("form :input[type='text']:enabled:first").focus();
});
</script>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:TextBox ID="tb1" runat="server" Enabled="false"/><br />
<
asp:TextBox ID="tb2" runat="server" Enabled="false"/><br />
<
asp:TextBox ID="tb3" runat="server"></asp:TextBox><br />
<
asp:TextBox ID="tb4" runat="server"></asp:TextBox><br />
<
asp:Button ID="Button1" runat="server" Text="Button" /><br />
</
div>
</
form>
</
body>
</
html>

OUTPUT

image

As you can observe, the focus is set to the third textbox since the first two are disabled.

September 7, 2009

Capture Shift, Alt and Ctrl Keys using jQuery

0 comments


A user mailed me a question:

I have a Form. If a user clicks on a Button control or clicks anywhere in the form holding the Shift, Alt or Ctrl Keys, I want to capture these keys and take a different action.

Here’s how to achieve this simple task:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Capture Shift, Alt and Ctrl Keys</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
$(document).click(function(e) {
if (e.shiftKey) {
alert("Shift pressed");
}
else if (e.ctrlKey) {
alert("Ctrl Pressed");
}
else if (e.altKey) {
alert("Alt Pressed");
}
});
</script>
</
head>
<
body>

</
body>
</
html>


image

September 6, 2009

How to Launch External Applications from Visual Studio 2005/2008

0 comments


Have you thought about launching external applications from Visual Studio? Although this may look obviously simple to a few, there are many who do not know how to launch external applications like Notepad, Calculator or for that matter any executable. Here’s how to launch external applications like Notepad from Visual Studio

Open Visual Studio 2008 > Go to Tools > External Tools

image

Click on ‘Add’ to add a new External Tool to the list. Set the ‘Title’ to Notepad and the ‘Command’ to the notepad.exe path, which in this case is ‘C:\Windows\Notepad.exe’

image

Click Ok. You can now access Notepad from the Tools Menu

image

How do I use the External Tool feature? Well I have Solitaire linked up in my External tools. Do I have to say more :)

September 5, 2009

Test your jQuery Selectors using this Cool Tool

0 comments


I recently stumbled upon the Interactive jQuery Tester tool created by Samuli Kärkkäinen and thought of letting you all know about this handy tool.

Using this tool, all you have to do is paste the markup in the right textarea labelled ‘Markup to test against’ and then type your selector in the textbox given at the top labelled ‘A jQuery selector expression (version 1.3.2):’. The tools automatically acts upon your selector and turns the matching elements to Green.

Let’s do a simple test. I want to test my selector expression and see if it selects all td’s greater than the index 3. I used the following markup

<table border="1">
<
tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<
tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<
tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</
table>

and the following selector expression against it

td:gt(3)

Observe that I have not added quotes in the selector expression while using it with the tool. In a normal scenario, I would have tested it using $("td:gt(3)")

The results are as shown below with the td’s greater than index 3, highlighted in Green

image

Nice tool! Go check it out!

September 4, 2009

Loop and Animate Elements of an Array using jQuery

1 comments


I stumbled across a recent thread where a user wanted to loop through an Array using jQuery and show the display the elements similar to a slide show. He wanted to avoid using the for loop and wanted to do it jQuery style. Here’s how to use the $.each() to achieve this requirement:

<html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
title>Loop through an array using jQuery</title>
<
script src="http://code.jquery.com/jquery-latest.js"
type="text/javascript"></script>
<
script type="text/javascript">
var
arrNames = ['Tom', 'Jane', 'Harry', 'Rick', 'Moby'];

$.each(arrNames, function(i, val) {
setTimeout(function() {
$('#divDisp').fadeOut("slow", function() {
$(this).text(val).fadeIn("slow");
});
}, i * 3000);
});
</script>
</
head>
<
body>
<
div id='divDisp'></div>
</
body>
</
html>

You can see a Live Demo.

 

Copyright © 2009-2011 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions