Check All Checkbox In GridView To Bulk Edit Or Update ASP.NET C# VB.NET

In this example i am going to describe how to implement CheckAll CheckBox in GridView to check all the rows in gridView.

For this i have put a checkBox in header Template of gridview which on checking will check all the rows in gridview using server side code.


Html Source of gridView

<asp:GridView ID="GridView1" runat="server"
DataSourceID="SqlDataSource1"
AutoGenerateColumns="false"
CellPadding="2" ForeColor="#333333"
GridLines="Both"
DataKeyNames="ID"
OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="CheckAll"
>
<
HeaderTemplate
>
<
asp:CheckBox ID="chkSelectAll" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelectAll_CheckedChanged"
/>
</
HeaderTemplate
>
<
ItemTemplate
>
<
asp:CheckBox ID="chkSelect" runat="server"
AutoPostBack="true"
OnCheckedChanged="chkSelect_CheckedChanged"/>
</ItemTemplate
>
</
asp:TemplateField>

<asp:BoundField DataField="ID" HeaderText="ID"
SortExpression="ID"/>
<asp:TemplateField HeaderText="Name" SortExpression="Name">
<ItemTemplate
>
<
asp:TextBox ID="txtName" runat="server"
Text='<%# Bind("Name") %>' ForeColor="Blue"
BorderStyle="none" BorderWidth="0px"
ReadOnly="true"
>
</
asp:TextBox
>
</
ItemTemplate
>
</
asp:TemplateField>

<asp:TemplateField HeaderText="Location" SortExpression
="Location">
<ItemTemplate>
<asp:TextBox ID="txtLocation" runat="server"
Text='<%# Bind("Location") %>'
ForeColor="Blue" BorderStyle="none"
ReadOnly="true">
</asp:TextBox
>
</
ItemTemplate
>
</
asp:TemplateField
>
</
Columns>
</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]"
DeleteCommand="DELETE FROM Details WHERE (ID = @ID)"

UpdateCommand
="UPDATE [Details] SET [Name] = @Name,
[Location] = @Location WHERE [ID] = @ID"
>
<DeleteParameters
>
<
asp:Parameter Name="ID" />
</DeleteParameters
>

<
UpdateParameters
>
<
asp:Parameter Name="Name" />
<asp:Parameter Name="Location"
/>
<
asp:Parameter Name="ID"
/>
</
UpdateParameters
>
</
asp:SqlDataSource>

<asp:Button ID="btnUpdate" runat="server"
OnClick="btnUpdate_Click" Text="Update" />
<asp:Button ID="btnDelete" runat="server"
OnClick="btnDelete_Click"
Text="Delete" />
C# Code behind

protected void chkSelectAll_CheckedChanged
(object sender, EventArgs e)
{
CheckBox chkAll =
(CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll");
if (chkAll.Checked == true)
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel =
(CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = true;
TextBox txtname = (TextBox)gvRow.FindControl("txtName");
TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
txtname.ReadOnly = false;
txtlocation.ReadOnly = false;
txtname.ForeColor = System.Drawing.Color.Black;
txtlocation.ForeColor = System.Drawing.Color.Black;
}
}
else
{
foreach (GridViewRow gvRow in GridView1.Rows)
{
CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect");
chkSel.Checked = false;
TextBox txtname = (TextBox)gvRow.FindControl("txtName");
TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation");
txtname.ReadOnly = true;
txtlocation.ReadOnly = true;
txtname.ForeColor = System.Drawing.Color.Blue;
txtlocation.ForeColor = System.Drawing.Color.Blue;
}
}
}

VB.NET code behind

Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs)
Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"),CheckBox)
If chkAll.Checked = True Then
For Each gvRow As GridViewRow In GridView1.Rows
Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"),CheckBox)
chkSel.Checked = True
Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
txtname.[ReadOnly] = False
txtlocation.[ReadOnly] = False
txtname.ForeColor = System.Drawing.Color.Black
txtlocation.ForeColor = System.Drawing.Color.Black
Next
Else
For Each gvRow As GridViewRow In GridView1.Rows
Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox)
chkSel.Checked = False
Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox)
Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox)
txtname.[ReadOnly] = True
txtlocation.[ReadOnly] = True
txtname.ForeColor = System.Drawing.Color.Blue
txtlocation.ForeColor = System.Drawing.Color.Blue
Next
End If
End Sub

If you have better solution, just tell me !

Ajax Autocomplete textbox add progress Image using javascript

In this example i m going to describe how to add animated Progress Image inside Ajax Auto complete extender textbox to represent loading of data.

For achieving this functionality i am using two different approaches for different versions of AjaxControlToolkit.dll


1st Approach

This approach is very simple and can be handy if you are using older/earlier version of AjaxControlToolkit (eg versions like 1.0.10201.0) which does not support css properties or properties like onclientpopulating. For this write the below mentioned javascript in head section of html markup of the aspx page.

<script type="text/javascript">
function ShowImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'url(images/loader.gif)';

document.getElementById('txtAutoComplete')
.style.backgroundRepeat= 'no-repeat';

document.getElementById('txtAutoComplete')
.style.backgroundPosition = 'right';
}
function HideImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'none';
}
</script>

In this script I've written two function to show and hide image, in the functions i m setting the background image style using document.getElementByID method , Now write this code in Page_Load event of aspx page.

protected void Page_Load(object sender, EventArgs e)
{
this.txtAutoComplete.Attributes.Add
("onkeypress", "ShowImage()");
this.txtAutoComplete.Attributes.Add
("onblur", "HideImage()");
}

Here i've added onblur and onkeypress attributes to textbox and calling respective function of javascript to show hide image.Build the solution and run ti see the results.

2nd approach

This approach works if you are using newer versions of AjaxControlToolkit.dll (Version 1.0.20229.20821 or later)
For this write the above mentioned javascript in head section of html markup of page.
Now in source of autocomplete extender add onclientpopulating="ShowImage" and onclientpopulated="HideImage".

<ajaxToolkit:AutoCompleteExtender runat="server"
ID="AutoComplete1"
BehaviorID="autoComplete"
TargetControlID="txtAutoComplete"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12"
CompletionListCssClass=
"autocomplete_completionListElement"
CompletionListItemCssClass=
"autocomplete_listItem"
CompletionListHighlightedItemCssClass=
"autocomplete_highlightedListItem"
onclientpopulating="ShowImage"
onclientpopulated="HideImage">
</ajaxToolkit:AutoCompleteExtender>

Complete html source of the page look like

<head runat="server">
<title>

Progress Image in AutoComplete TextBox

</title>
<script type="text/javascript">
function ShowImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'url(images/loader.gif)';

document.getElementById('txtAutoComplete')
.style.backgroundRepeat= 'no-repeat';

document.getElementById('txtAutoComplete')
.style.backgroundPosition = 'right';
}
function HideImage()
{
document.getElementById('txtAutoComplete')
.style.backgroundImage = 'none';
}
</script>
</head>
<body>
<
form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="AutoComplete.asmx" />
</Services>
</
asp:ScriptManager>
<
br />
<
div>
<
asp:TextBox ID="txtAutoComplete" runat="server" Width="252px">
</
asp:TextBox><br />
<
ajaxToolkit:AutoCompleteExtender runat="server"
ID="AutoComplete1"
BehaviorID="autoComplete"
TargetControlID="txtAutoComplete"
ServicePath="AutoComplete.asmx"
ServiceMethod="GetCompletionList"
MinimumPrefixLength="1"
CompletionInterval="10"
EnableCaching="true"
CompletionSetCount="12"
CompletionListCssClass=
"autocomplete_completionListElement"
CompletionListItemCssClass=
"autocomplete_listItem"
CompletionListHighlightedItemCssClass=
"autocomplete_highlightedListItem"
onclientpopulating="ShowImage"
onclientpopulated="HideImage">
</ajaxToolkit:AutoCompleteExtender>
</div>
</form>

If you have better solution, just tell me !

Adding and using jQuery on Blogger / Blogspot

Investigating my visitors statistics, I noticed that there were some users who were interested in adding and using jQuery on their Blogger.com (Blogspot.com) accounts. Adding jQuery library to your Blogger/Blogspot blog is not difficult. All you have to do is to add one line of code to your template’s header.

Here is the code to add to your blogger template’s header:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6
/jquery.min.js" type="text/javascript"
></script>
NOTE:

You don’t even need to upload jquery.js file on any other hosting Google will host it for your.

Instruction for adding jQuery to Blogger:

Login to your dashboard;
Choose your blog;
From the top menu select “Layout”;
Then select “Edit HTML” sub-menu;
Add the above code just below tag (or alternatively, just above tag)

If you have better solution, just tell me !

jQuery AJAX functions (load(), $.get(), etc.) are not loading new page versions problem

Today I would like to share with you a quick solution to the common problem when your AJAX calls to some page that changes over time is not being loaded to your page. In other words, jQuery or your browser is not loading new version of the page.

This problem is common in Mozilla Firefox (FF). Internet Explorer (IE) users I believe, do not experience this problem. Usually it occurs when you use jQuery AJAX functions in javascript setInterval() method. Basically, what happens is that Firefox can not see the changes been made to the page and thinks it’s the same with the old one. So Firefox loads it from cache and you don’t see the new version of your page. To resolve this issue, you should simply add a random string to the request like below.

The solution:

// Reload mypage.html every 5 seconds
var refresh = setInterval(function()
{
// Minimized code, suggested by Kovacs
$('#mydiv').load("mypage.htm?" + 1*new Date() );

}, 5000);

If you have better solution, just tell me !

Problems with jQuery mouseover / mouseout events

Today I have a quick note for you that will probably save you time someday. Basically it’s a workaround for a bug when you have parent element with children elements and parent element has mouseover or mouseout event. Moving your mouse over children elements may fire mouseout event of their parent. This is caused by event bubbling / propagation and if you would like to have a quick solution just read the solution at the bottom of this post. If you would like to understand it in more details please search Google for event propagation.

The problem:
When you have mouseover and mouseout events bound to some element on you page with children elements. Hovering over children element fires parent’s mouseover and/or mouseout event.
The solution:
The solution to this error is to use mouseenter and mouseleave events instead of mouseover and mouseout.
The reason:
This solution works because mouseover and mouseout events do not bubble from child to parent element.

Javascript for() loop vs jQuery .each() performance comparison

This post is an outcome of 15 minutes of free time and a question that I had yesterday. This question were:

How fast jQuery’s .each() method is?
How does it compare to javascript’s native for loop?
It is clear without any performance tests that native javascript for loop is faster, but I always used jQuery’s .each() utility with caution. It always felt like I will get a performance penalty for using it. So I tried to never use it.

So today, I wrote up a little javascript performance test and got my answers. Basically, I created an array and iterated through it using native for loop and jQuery’s .each() iterator. All I did was just an iteration and no array amendments or any other logic. I know it is very basic, but that’s exactly what I want to know. How fast they iterate!

Performance test code:

console.time('TestNative');
for( i=0; i < myArray.length; i++){
myArray[i];
}
console.timeEnd('TestNative');

console.time('TestjQuery');
jQuery.each(myArray, function(i, val) {
val;
});
console.timeEnd('TestjQuery');

Performance test results:

JavaScript Native FOR loop

Array size Time
========== ======

10,000 7ms
100,000 62ms
1,000,000 613ms


jQuery .each() loop

Array size Time
========== ======

10,000 10ms
100,000 177ms
1,000,000 1100ms


Usually we don’t have more than 1000 items in our arrays and objects, that is why I guess it can be concluded that using .each() loop in our code will not cause any performance penalties.

Dynamically adding table row count number using JavaScript and jQuery

Recently on jQuery mailing list a user asked how he/she could add a row count in their table automatically. So I wrote a code snippet which looks like this:

$(document).ready(function(){
$("table").each(function(){
if($(this).is('table')){
$('thead th:first-child, thead td:first-child', this).each(
                                                   function(){
if($(this).is('td'))
$(this).before('<td>#</td>');
else if($(this).is('th'))
$(this).before('<th>#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
});

This code was for specific case, where there is only one table on the page and it has only one row in its header. That is why I took into the account the possibility of row spans and multi line rows in header and rewrote the code. Then made a plugin out of it. So, here is the final code:

function($){
$.fn.extend({
addCount: function() {
return $(this).each(function(){
if($(this).is('table')){
$('thead th:first, thead td:first', this).each(function(){
if($(this).is('td'))
$(this).before('<td rowspan="'+$('thead tr').length+'">#</td>');
else if($(this).is('th'))
$(this).before('<th rowspan="'+$('thead tr').length+'">#</th>');
});
$('tbody td:first-child', this).each(function(i){
$(this).before('<td>'+(i+1)+'</td>');
});
}
});
}
});
})(jQuery);

To apply it to your tables use this code:

$('table').addCount();
$('.some-table-class').addCount();
$('#some-table-id').addCount();

If you have better solution, just tell me !