Check/Uncheck all items in a CheckBoxList using ASP.NET and Javascript

The CheckBoxList control in ASP.NET 2.0 provides a group of checkboxes that can be dynamically generated by binding it to a data source. In this article, we will explore how to use a Checkboxlist and use ASP.NET and Javascript to select or unselect all your checkboxes in your CheckBoxList.
Using ASP.NET
Step 1: Open Visual Studio. Create a new website called ‘CheckUncheckAll’. Drag and drop a CheckBoxList control to the page. Rename it to ‘cblMulti’.
Step 2: Once the CheckBoxList is added to the page, a smart tag appears which allows you to specify a datasource or add items manually to the CheckBoxList. Click on the ‘Edit Items’ to open the ListItem Collection Editor and add items as shown in the figure below :
Note: If you do not want to use the editor and want to add items to the CheckBoxList programmatically, use the following code at the Page load event :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cblMulti.Items.Add(new ListItem("Items 1", "Items 1"));
cblMulti.Items.Add(new ListItem("Items 2", "Items 2"));
cblMulti.Items.Add(new ListItem("Items 3", "Items 3"));
}
}
However, you can also bind the checkbox list to a datareader as show below :
// Assuming that GetListItems returns a list of customerid and customername items in a sqldatareader
SqlDataReader dr = GetListItems();
cblMulti.DataSource = dr;
cblMulti.DataValueField = "cust_no";
cblMulti.DataTextField = "cust_name";
cblMulti.DataBind();
To keep things simple, we will be adding items programatically by using the cblMulti.Items.Add(new ListItem(text,value)) in our example.
Step 3: Drag and drop two LinkButtons from the toolbox to the page and rename them as ‘lbAll’ and ‘lbNone’ respectively.
The code will look like this :
<asp:LinkButton ID="lbAll" runat="server">Select Allasp:LinkButton>
<asp:LinkButton ID="lbNone" runat="server">Select Noneasp:LinkButton>
Step 4: Double click the two ‘Link Button’ to generate the click events for them. In the click events of the two Link Buttons(), add the following code:
// Check All
protected void lbAll_Click(object sender, EventArgs e)
{
foreach (ListItem li in cblMulti.Items)
{
li.Selected = true;
}
}
// Uncheck All
protected void lbNone_Click(object sender, EventArgs e)
{
foreach (ListItem li in cblMulti.Items)
{
li.Selected = false;
}
}
Step 5 : Run the application and test it. Click on the ‘Select All’ button to select all the checkboxes at once. Similarly click on the ‘Select None’ button to deselect all the checkboxes at once.
So that was simple.
Using Javascript
We can do the same using javascript. However for our javascript example, let us add some complexity into our examples. We will take a master page example, and will now add two checkboxlist instead of one to our page. Follow these steps :
Step 1: Open Visual Studio. Create a new website called ‘CheckUncheckJS’. Drag and drop two CheckBoxList controls to the page. Rename it to ‘cbl1’ and ‘cbl2’.
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:CheckBoxList ID="cbl1" runat="server">
asp:CheckBoxList><br />
<asp:CheckBoxList ID="cbl2" runat="server">
asp:CheckBoxList>
asp:Content>
Step 2: Populate the two checkboxlist controls in the Page_Load()
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
cbl1.Items.Add(new ListItem("Items 1", "Items 1"));
cbl1.Items.Add(new ListItem("Items 2", "Items 2"));
cbl1.Items.Add(new ListItem("Items 3", "Items 3"));
cbl2.Items.Add(new ListItem("Items 4", "Items 4"));
cbl2.Items.Add(new ListItem("Items 5", "Items 5"));
cbl2.Items.Add(new ListItem("Items 6", "Items 6"));
}
}
Step 3: It’s time to add the SelectAll/None feature to our page. However before we go ahead, we need to understand how to pass the controls kept in content pages to the javascript function. When the page is rendered in the browser, the content and master pages get merged into a single page. This means that the IDs for the controls get renamed. ASP.NET renames the IDs to prevent naming conflicts. Now to handle the renamed controls, ASP.NET provides the ‘Control.ClientID’ and ‘Control.UniqueID’ to get the renamed ID’s.
Having understood this, let us now add some controls to our page and then pass the respective controls to the javascript using the Control.ClientID.
The prototype of our javascript function will be the following :
function CheckBoxListSelect(, )
{
// Our code will come here
}
Step 4: Add two anchor tags beneath each checkboxlist controls in your source. Remember that we are using two checkboxlist controls.
<asp:CheckBoxList ID="cbl1" runat="server">asp:CheckBoxList><br />
Select <a id="A1" href="#">Alla> | <a id="A2" href="#">Nonea>
<asp:CheckBoxList ID="cbl2" runat="server">asp:CheckBoxList><br />
Select <a id="A3" href="#">Alla> | <a id="A4" href="#">Nonea>
Step 5: Add the onclick event to the anchor tags as shown below. In this event, we will call the javascript function and pass the respective checkboxlist controls and the state which will describe ‘true’ or ‘false’ for each checkbox
The code at the end will look like this :
<asp:CheckBoxList ID="cbl1" runat="server">asp:CheckBoxList><br />
Select <a id="A1" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',true)">Alla>
| <a id="A2" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl1.ClientID %>',false)">Nonea>
<br />
<br />
<asp:CheckBoxList ID="cbl2" runat="server">
asp:CheckBoxList>
Select <a id="A3" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl2.ClientID %>',true)">Alla>
| <a id="A4" href="#" onclick="javascript: CheckBoxListSelect ('<%= cbl2.ClientID %>',false)">Nonea>
Step 6: Let us add the javascript function to the content page now.
For this add the

Deleting Multiple Rows in a GridView

If you have used Hotmail or any other similar email client, you might have observed that we have the option of selecting multiple rows (using the checkbox provided) and perform a set of operations on them. In this article, we will replicate this scenario for a gridview. A gridview allows us to delete only a single row at a time. We will extend this functionality to select multiple rows and delete all of the selected rows in a single stroke. In this article, I assume that you are aware of creating asp.net web applications and have worked with gridview.
The sample makes use of the Northwind database. We will be pulling data from the Employee table. For this sample to work, drop all the Foreign Key relationships on the Employee Table. To do so, in Sql Server Management Studio, browse to the Northwind database and open the Employee table in design view. Right click in the Table designer on the right hand side and choose ‘Relationships’. Select all the relationships like FK_Orders_Employees, FK_EmployeeTerritories_Employees etc and delete them. This step is necessary as we will get a constraint violation exception if we do not do so.
Once we are through with the task of removing the relationships in the Employee table, let us explore the steps to create a gridview with functionality to delete multiple rows at a time.
Perform the following steps :
Step 1: Create an .aspx page and add a GridView and a SqlDataSource control to it.
Step 2: Configure the connection of SqlDataSource to point to the Northwind database. Create queries for the Select and Delete commands. The resultant code will look similar as given below :
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
<DeleteParameters>
<asp:Parameter Name="EmployeeID" />
DeleteParameters>
asp:SqlDataSource>
Step 3: Once the SqlDataSource has been configured, bind the gridview with this data source.
Step 4: To create a checkbox in each row, follow these steps:
1. Create a TemplateField inside the <Columns> to add custom content to each column.
2. Inside the TemplateField, create an ItemTemplate with a CheckBox added to it.
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkRows" runat="server"/>
ItemTemplate>
asp:TemplateField>
This will add a checkbox to each row in the grid.
Step 5: Add a button control, and rename it to btnMultipleRowDelete.
The resultant markup in the design view will look similar to the code below :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="EmployeeID" DataSourceID="SqlDataSource1">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cbRows" runat="server"/>
ItemTemplate>
asp:TemplateField>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False" ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
Columns>
asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" Runat="server"
SelectCommand="SELECT EmployeeID, LastName, City FROM Employees"
DeleteCommand="DELETE FROM Employees WHERE [EmployeeID] = @EmployeeID"
ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>" >
<DeleteParameters>
<asp:Parameter Name="EmployeeID" />
DeleteParameters>
asp:SqlDataSource>
<asp:Button
ID="btnMultipleRowDelete"
OnClick="btnMultipleRowDelete_Click"
runat="server"
Text="Delete Rows" />
In Code behind file (.cs) for C# and (.vb) for VB.NET, code the button click event. Our code will first loop through all the rows in the GridView. If a row is checked, the code retrieves the EmployeeID and passes the selected value to the Delete Command.
C#
protected void btnMultipleRowDelete_Click(object sender, EventArgs e)
{
// Looping through all the rows in the GridView
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox checkbox = (CheckBox)row.FindControl("cbRows");
//Check if the checkbox is checked.
//value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.
if (checkbox.Checked)
{
// Retreive the Employee ID
int employeeID = Convert.ToInt32(GridView1.DataKeys[row.RowIndex].Value);
// Pass the value of the selected Employye ID to the Delete //command.
SqlDataSource1.DeleteParameters["EmployeeID"].DefaultValue = employeeID.ToString();
SqlDataSource1.Delete();
}
}
}
VB.NET

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

' Looping through all the rows in the GridView

For Each row As GridViewRow In GridView1.Rows

Dim checkbox As CheckBox = CType(row.FindControl("cbRows"), CheckBox)

'Check if the checkbox is checked.

'value in the HtmlInputCheckBox's Value property is set as the //value of the delete command's parameter.

If checkbox.Checked Then

' Retreive the Employee ID

Dim employeeID As Integer = Convert.ToInt32(GridView1.DataKeys(row.RowIndex).Value)

' Pass the value of the selected Employye ID to the Delete //command.

SqlDataSource1.DeleteParameters("EmployeeID").DefaultValue = employeeID.ToString()

SqlDataSource1.Delete()

End If

Next row

End Sub

Run the code, and select a few rows in the grid. ‘Delete Rows’ button, the selected rows get deleted. Rather than deleting rows one at a time, deleting them in a batch is a good practice. I would encourage you to read Scott Mitchell’s article for the same.

How to open popup windows in IE/Firefox and return values using ASP.NET and Javascript

With the forums flooded with questions of opening a popup window, passing values to the popup window and then return values back to the parent page using both Internet Explorer and Firefox, I decided to take a plunge into the subject and experiment with an easy implementation. This article explains how to transfer values between the Parent page and a Pop-up window. The code has been tested against IE7 and Firefox.
Internet Explorer(IE) contains the showModalDialog() method which proves very effective while creating a modal dialog box and displaying a html document in it. One caveat being, showModalDialog() is not a W3C implementation. So it is not supported in Firefox (as of version 2.0.0.11). Firefox supports the window.open() method. However there is no built in functionality in Firefox that keeps the popup modal. At the most, you can use ‘modal=yes’ to make the popup appear in front. However unlike the showModalDialog() in IE, you cannot restrict the user to access the parent page when the popup is opened in Firefox. In short, it is not truly modal. There are different ways to get around this problem, however in this article, we will only focus on exchanging values between the parent and popup page.
In this article, we will see how to take a simple approach and create a popup window using both IE and Firefox. In the first part, we will pass in the first name from the parent page to the popup window. In the second part, the popup window will reverse the name and return the reversed string to the parent window. All set!! Let us get started.
Part 1 - Passing value to Popup window
Step 1: Open Visual Studio. Create a new website (File > New > Website). Set the location, filename and language of the project.
Step 2: In your Default.aspx, add a label (lblFName), textbox (txtFName) and a button (btnPopup). Set the ‘Text’ property of the label to ‘FirstName’. Similarly set the ‘Text’ property of the button control to ‘Show Popup’.
Step 3: Now add the popup form. Right click your project > Add New Item > Web Form > Rename form as ‘PopupWin.aspx’ and click on Add.
Step 4: In the PopupWin.aspx, add a textbox (txtReverse) and a button (btnReverse).
Well now we have two pages, Default.aspx which is the parent page and PopupWin.aspx which will be the popup page. Let us now pass a value from Default.aspx to the popup window.
Step 5: We will invoke the popup window on the button (btnPopup) click of Default.aspx. To do so, we will use Button.Attribute.Add and call a javascript function that will open the popup window. The javascript function will be contained in a seperate pop.js file which we will create shortly. Add this code in the code behind file of your Default.aspx.
C#
protected void Page_Load(object sender, EventArgs e)
{
btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" + txtFName.ClientID + "');");
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
btnPopup.Attributes.Add("onClick", "javascript:InvokePop('" & txtFName.ClientID & "');")
End Sub
Over here we are passing the ClientID of the textbox. ClientID is the identifier of the server control, generated by ASP.NET. You must be wondering why I am not passing the value of the textbox directly. Well passing the control has an advantage where there is more than one control that is passed to the popup page. While returning back the values from the popup to the parent page; it helps you to decide and determine which control receives which value. Even though we will be using only one textbox for simplicity, I thought of creating a sample which can be extended later by you to suit your needs. If the use of ClientID is not clear to you, wait till we get to part 2 of this article, and I will again touch upon the subject.
Step 6: Let us now create the javascript functionality which will open the Popup. Right click your project > Add New Item > Jscript file > Rename the file to pop.js. Add the following function to the pop.js file
function InvokePop(fname)
{
val = document.getElementById(fname).value;
// to handle in IE 7.0
if (window.showModalDialog)
{
retVal = window.showModalDialog("PopupWin.aspx?Control1=" + fname + "&ControlVal=" + val ,'Show Popup Window',"dialogHeight:90px,dialogWidth:250px,resizable:
yes,center:yes,");
document.getElementById(fname).value = retVal;
}
// to handle in Firefox
else
{
retVal = window.open("PopupWin.aspx?Control1="+fname + "&ControlVal=" + val,'Show Popup Window','height=90,width=250,resizable=yes,modal=yes');
retVal.focus();
}
}
This function accepts the textbox control, retrieve’s the value of the textbox that needs to be reversed and passes the textbox control and its value to PopupWin.aspx through query string. This is the function which will be called on the btnPopup click.
Step 7: To wire up the .js with your asp.net pages, add a link to the javascript file in both the pages as shown below:
Default.aspx
<head runat="server">
<title>Parent Pagetitle>
<script type="text/javascript" src="pop.js">script>
head>
PopupWin.aspx
<head runat="server">
<title>Popup Pagetitle>
<script type="text/javascript" src="pop.js">script>
head>
Step 8: In the code behind file of PopupWin.aspx, add the following code at the Page_Load() to retrieve the value from the querystring and display the value in the TextBox ‘txtReverse’, placed in the popup window.
C#
protected void Page_Load(object sender, EventArgs e)
{
txtReverse.Text = Request.QueryString["ControlVal"].ToString();
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
txtReverse.Text = Request.QueryString("ControlVal").ToString()
End Sub
If you are eager to test the value going from Parent page to the popup window, you can do so now. Make Default.aspx as ‘Set as Start page’ and run the sample. Enter your name in txtFName TextBox and click on Show Popup button. A popup window opens with the value entered in the Parent page.
Part 2 - Passing value from Popup window to the Parent page
In this second part, we will reverse the string and pass the reversed string back to the parent page. To do so, follow these steps:
Step 1: Add additional functions to the pop.js file which will reverse the string and return the string back to the parent page.
// pop.js
function ReverseString()
{
var originalString = document.getElementById('txtReverse').value;
var reversedString = Reverse(originalString);
RetrieveControl();
// to handle in IE 7.0
if (window.showModalDialog)
{
window.returnValue = reversedString;
window.close();
}
// to handle in Firefox
else
{
if ((window.opener != null) && (!window.opener.closed))
{
// Access the control.
window.opener.document.getElementById(ctr[1]).value = reversedString;
}
window.close();
}
}
function Reverse(str)
{
var revStr = "";
for (i=str.length - 1 ; i > - 1 ; i--)
{
revStr += str.substr(i,1);
}
return revStr;
}
function RetrieveControl()
{
//Retrieve the query string
queryStr = window.location.search.substring(1);
// Seperate the control and its value
ctrlArray = queryStr.split("&");
ctrl1 = ctrlArray[0];
//Retrieve the control passed via querystring
ctr = ctrl1.split("=");
}
As you saw in part 1, the value was passed from the parent window to the popup window and was kept in the txtReverse TextBox. The function ReverseString() retrieves the value from this textbox and passes the string to the Reverse() function which reverses the string. The reversed string is then kept in the ‘reversedString’ variable. The ‘RetrieveControl’ splits the query string and identifies the control in the parent page to which the reversed string value is to be sent.
Note: If you observe, in the IE implementation, I am not really making use of the RetrieveControl(), however in Firefox I am. If you remember, in the beginning of part1 , I had mentioned the use of ClientID, using which both controls and their values can be passed to determine which control recieves which value. This is especially needed when there are multiple controls. Well the RetrieveControl seperates the different controls and you can use the variables in this method to return values to the respective contro.l
The value is then returned to the parent window and the popup window is closed.
Step 2: Now in order to use these newly added javacript functions, just call the ReverseString() function on the btnReverse click. To do so, add the onclick attribute to the btnReverse.
<input class="button" type="button" id="btnReverse" value="Reverse value back" onclick="ReverseString();"/>
That’s it. Now test the code. Pass your name from the Parent window to the Popup window and then reverse the string and pass it back to the Parent window.
I would like to mention that there are multiple ways of doing the task demoed in this article. I have seen some cool examples by experts. One of them I would like to mention is that of NC01 where he makes use of properties and ViewState, to pass values to the Popup window. I would encourage you to use this article as a base and try out your own implementations that would work on multiple browsers.

GridView Tips and Tricks using ASP.NET 2.0

The GridView control is quiet a handy control and is the most commonly used control when building an ASP.NET site. The more you work with it, the more you realize how powerful it can be while presenting data. In this article, we will explore some of the most frequently asked questions about the GridView control. The article discusses ten tips and tricks that you can use while using the GridView control.
Tip 1: Add, Update, Delete Records in a Gridview using SqlDataSource
By default, the GridView control doesn’t have support for inserting new records. However you can use the built-in edit or delete functionality of the GridView control. Let us explore how to insert new records and Update and Delete existing records in Gridview. Just copy and paste the code in your project. We will be using the ‘Categories’ table in the ‘Northwind’ database.
GridView.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView.aspx.cs" Inherits="GridView" %>
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>Grid View Add Update Deletetitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
DataSourceID="SqlDataSource1" ShowFooter="true" AllowPaging="True" AllowSorting="True" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"/>
<asp:TemplateField HeaderText="CategoryID" InsertVisible="False" SortExpression="CategoryID">
<EditItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("CategoryID") %>'>asp:Label>
EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CategoryID") %>'>asp:Label>
ItemTemplate>
asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName" SortExpression="CategoryName">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CategoryName") %>'>asp:TextBox>
EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("CategoryName") %>'>asp:Label>
ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="CategoryNameTextBox" Runat="server">asp:TextBox>
FooterTemplate>
asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Description") %>'>asp:TextBox>
EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("Description") %>'>asp:Label>
ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="DescriptionTextBox" Runat="server">asp:TextBox>
FooterTemplate>
asp:TemplateField>
<asp:templatefield>
<footertemplate>
<asp:linkbutton id="btnNew" runat="server" commandname="New" text="New" />
footertemplate>
asp:templatefield>
Columns>
asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="Data Source=SUPROTIM;Initial Catalog=Northwind;Integrated Security=True"
DeleteCommand="DELETE FROM [Categories] WHERE [CategoryID] = @CategoryID" InsertCommand="INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)"
ProviderName="System.Data.SqlClient" SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]"
UpdateCommand="UPDATE [Categories] SET [CategoryName] = @CategoryName, [Description] = @Description WHERE [CategoryID] = @CategoryID">
<DeleteParameters>
<asp:Parameter Name="CategoryID" Type="Int32" />
DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
<asp:Parameter Name="CategoryID" Type="Int32" />
UpdateParameters>
<InsertParameters>
<asp:Parameter Name="CategoryName" Type="String" />
<asp:Parameter Name="Description" Type="String" />
InsertParameters>
asp:SqlDataSource>
div>
form>
body>
html>
GridView.aspx.cs
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conn = new SqlConnection(
ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString);
try
{
if (e.CommandName.Equals("New"))
{
LinkButton btnNew = e.CommandSource as LinkButton;
GridViewRow row = btnNew.NamingContainer as GridViewRow;
if (row == null)
{
return;
}
TextBox txtCatName = row.FindControl("CategoryNameTextBox") as TextBox;
TextBox txtDescription = row.FindControl("DescriptionTextBox") as TextBox;
SqlCommand cmd = new SqlCommand(
"INSERT INTO [Categories] ([CategoryName], [Description]) VALUES (@CategoryName, @Description)",
conn);
cmd.Parameters.AddWithValue("CategoryName", txtCatName.Text);
cmd.Parameters.AddWithValue("Description",txtDescription.Text);
conn.Open();
if (cmd.ExecuteNonQuery() == 1)
{
GridView1.DataBind();
}
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
Web.config
<connectionStrings>
<addname="NorthwindConnectionString"connectionString="Data Source =.;Integrated Security = SSPI; Initial Catalog=Northwind;"/>
connectionStrings>
Tip 2: Paging and Sorting a GridView without Refreshing a Page
If you have created a GridView and have bound it to a data source control, you can avoid postback during sorting and paging by setting ‘EnableSortingAndPagingCallbacks’ property of the GridView to True.
Just remember that when you set the 'EnableSortingAndPagingCallbacks' property to true, you cannot use Template Fields in the GridView.
Tip 3: Pop-up a Confirmation box before Deleting a row in GridView
Add a template field and drop a button in it, using which the user will delete the record. In the OnClientClick event, call the confirm() function as mentioned below:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDel" runat="server" Text="Delete"
CommandName="Delete" OnClientClick="return confirm('Are you sure you want to delete the record?');" />
ItemTemplate>
asp:TemplateField>
Tip 4: Display details of the Row selected in the GridView
Assuming you have a button called ‘Select’ in your GridView with CommandName ‘Select’, to find out the row clicked and display the row’s details, use this code:
C#
private void GridView1_RowCommand(Object sender,
GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int idx = Convert.ToInt32(e.CommandArgument);
GridViewRow selrow = GridView1.Rows[idx];
string fstCell = selrow.Cells[0].Text;
string scndCell = selrow.Cells[1].Text;
// and so on
// Thanks to Mark Rae (MVP) for pointing the typo. Earlier it was Cells[1] and Cells [2]
}
}
VB.NET
Private Sub GridView1_RowCommand(ByVal sender As Object, ByVal e As GridViewCommandEventArgs)
If e.CommandName = "Select" Then
Dim idx As Integer = Convert.ToInt32(e.CommandArgument)
Dim selrow As GridViewRow = GridView1.Rows(idx)
Dim fstCell As String = selrow.Cells(0).Text
Dim scndCell As String = selrow.Cells(1).Text
' and so on
End If
End Sub
Tip 5: Retrieve Details of the Row being Modified in GridView
C#
void GridView1_RowUpdated(Object sender, GridViewUpdatedEventArgs e)
{
// Retrieve the row being edited.
int index = GridView1.EditIndex;
GridViewRow row = GridView1.Rows[index];
// Retrieve the value of the first cell
lblMsg.Text = "Updated record " + row.Cells[1].Text;
}
VB.NET
Private Sub GridView1_RowUpdated(ByVal sender As Object, ByVal e As GridViewUpdatedEventArgs)
' Retrieve the row being edited.
Dim index As Integer = GridView1.EditIndex
Dim row As GridViewRow = GridView1.Rows(index)
' Retrieve the value of the first cell
lblMsg.Text = "Updated record " & row.Cells(1).Text
End Sub
Tip 6: Retrieve Details of the Row being Deleted in GridView
The ID of the row being deleted must be in the GridView.DataKeyNames collection.
C#
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
// Query the database and get the values based on the ID
}
VB.NET
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
Dim ID As Integer = CInt(GridView1.DataKeys(e.RowIndex).Value)
' Query the database and get the values based on the ID
End Sub
Tip 7: Cancelling Update and Delete in a GridView
RowUpdating - Occurs when a row's Update button is clicked, but before the GridView control updates the row.
RowDeleting – Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.
C#
protected void gvDetail_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
e.Cancel = true;
}
void GridView1_RowDeleting(Object sender, GridViewDeleteEventArgs e)
{
// Check for a condition and cancel the delete
// There should be atleast one row left in the GridView
if (GridView1.Rows.Count <= 1)
{
e.Cancel = true;
}
}
VB.NET
Protected Sub gvDetail_RowUpdating(ByVal sender As Object, ByVal e As GridViewUpdateEventArgs)
e.Cancel = True
End Sub
Private Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As GridViewDeleteEventArgs)
' Check for a condition and cancel the delete
' There should be atleast one row left in the GridView
If GridView1.Rows.Count <= 1 Then
e.Cancel = True
End If
End Sub
Tip 8: Paging and Sorting in GridView without using Datasource control
Original Code Author: Ryan Olshan
C#
<asp:GridView ID="gridView" OnPageIndexChanging="gridView_PageIndexChanging"
OnSorting="gridView_Sorting" runat="server" />
private string ConvertSortDirectionToSql(SortDirection sortDireciton)
{
string newSortDirection = String.Empty;
switch (sortDirection)
{
case SortDirection.Ascending:
newSortDirection = "ASC";
break;
case SortDirection.Descending:
newSortDirection = "DESC";
break;
}
return newSortDirection
}
protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gridView.PageIndex = e.NewPageIndex;
gridView.DataBind();
}
protected void gridView_Sorting(object sender, GridViewSortEventArgs e)
{
DataTable dataTable = gridView.DataSource as DataTable;
if (dataTable != null)
{
DataView dataView = new DataView(dataTable);
dataView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
gridView.DataSource = dataView;
gridView.DataBind();
}
}
VB.NET
Private Function ConvertSortDirectionToSql(ByVal sortDireciton As SortDirection) As String
Dim newSortDirection As String = String.Empty
Select Case sortDirection
Case SortDirection.Ascending
newSortDirection = "ASC"
Case SortDirection.Descending
newSortDirection = "DESC"
End Select
Return newSortDirection
End Function
Protected Sub gridView_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
gridView.PageIndex = e.NewPageIndex
gridView.DataBind()
End Sub
Protected Sub gridView_Sorting(ByVal sender As Object, ByVal e As GridViewSortEventArgs)
Dim dataTable As DataTable = TryCast(gridView.DataSource, DataTable)
If Not dataTable Is Nothing Then
Dim dataView As DataView = New DataView(dataTable)
dataView.Sort = e.SortExpression & " " & ConvertSortDirectionToSql(e.SortDirection)
gridView.DataSource = dataView
gridView.DataBind()
End If
End Sub
Tip 9: Delete Multiple rows in a GridView
Check this article of mine over here.
Tip 10: Export GridView To Excel
C#
protected void Button1_Click(object sender, EventArgs e)
{
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Response.Charset = String.Empty;
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter sw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Write(sw.ToString());
Response.End();
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Response.Charset = String.Empty
Response.ContentType = "application/vnd.xls"
Dim sw As System.IO.StringWriter = New System.IO.StringWriter()
Dim hw As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(sw)
GridView1.RenderControl(hw)
Response.Write(sw.ToString())
Response.End()
End Sub
Well that was a quick overview of some of the most frequently used features of the GridView control. I hope you liked the article and I thank you for viewing it.

Detect Browser Compatibility with the Request Object

Use JavaScript to set up Microsoft's and the Mozilla-based browsers' different request objects.

Browser compatibility is an important consideration. You have to make sure the "engine" behind Ajax's server handshake is properly constructed, but you can never predict which browsers your users will favor.

The programming tool that allows Ajax applications to make HTTP requests to a server is an object that you can use from within JavaScript code. In the world of Firefox and Netscape (as well as Safari and Opera), this object is named XMLHttpRequest. However, continuing with the tradition established by IE 5.0, recent vintages of Internet Explorer implement the software as an ActiveX object named Microsoft.XMLHTTP or Msxml2.XMLHTTP.

Although Microsoft and the engineers on the Mozilla project have chosen to implement this object differently, we will refer to the ActiveX and XMLHttpRequest objects simply as "request objects" throughout this book, because they have very similar functionality.

As a first step in using Ajax, you must check if the user's browser supports either one of the Mozilla-based or ActiveX-related request objects, and then properly initialize the object.

Using a Function for Checking Compatibility

Wrap the compatibility check inside a JavaScript function, then call this function before you make any HTTP requests using the object. For example, in Mozilla-based browsers such as Netscape 7.1 and Firefox 1.5 (as well as in Safari 2.0 and Opera 8.5), the request object is available as a property of the top-level window object. The reference to this object in JavaScript code is window.XMLHttpRequest. The compatibility check for these browser types looks like this:

if(window.XMLHttpRequest){
request = new XMLHttpRequest( );
request.onreadystatechange=handleResponse;
request.open("GET",theURL,true);
request.send(null);
}

The JavaScript variable request is to a top-level variable that will refer to the request object.

If the browser supports XMLHttpRequest, then:

  1. if(window.XMLHttpRequest) returns true because the XMLHttpRequest is not null or undefined.

  2. The object will be instantiated with the new keyword.

  3. Its onreadystatechange event listener (see the section "XMLHttpRequest" earlier in this chapter) will be defined as a function named handleResponse( ).

  4. The code calls the request object's open( ) and send( ) methods.

In this case, the window.XMLHttpRequest object will not exist in the browser object model. Therefore, another branch of the if test is necessary in your code:

else if (window.ActiveXObject){
request=new ActiveXObject("Microsoft.XMLHTTP");
if (! request){
request=new ActiveXObject("Msxml2.XMLHTTP");
}
if(request){
request.onreadystatechange=handleResponse;
request.open(reqType,url,true);
request.send(null);
}
}

This code fragment tests for the existence of the top-level window object ActiveXObject, thus signaling the use of Internet Explorer. The code then initializes the request using two of a number of possible ActiveX program IDs (here, Microsoft.XMLHTTP and Msxml2.XMLHTTP).

You can get even more fine-grained when testing for different versions of the IE request object, such as Msxml2.XMLHTTP.4.0. In the vast majority of cases, however, you will not be designing your application based on various versions of the MSXML libraries, so the prior code will suffice.

The code then makes one final check for whether the request object has been properly constructed (if(request){...}).

Given three chances, if the request variable is still null or undefined, your browser is really out of luck when it comes to using the request object for Ajax!

Here's an example of an entire compatibility check:

/* Wrapper function for constructing a request object.
Parameters:
reqType: The HTTP request type, such as GET or POST.
url: The URL of the server program.
asynch: Whether to send the request asynchronously or not. */

function httpRequest(reqType,url,asynch){
//Mozilla-based browsers
if(window.XMLHttpRequest){
request = new XMLHttpRequest( );
} else if (window.ActiveXObject){
request=new ActiveXObject("Msxml2.XMLHTTP");
if (! request){
request=new ActiveXObject("Microsoft.XMLHTTP");
}
}
//the request could still be null if neither ActiveXObject
//initialization succeeded
if(request){
initReq(reqType,url,asynch);
} else {
alert("Your browser does not permit the use of all "+
"of this application's features!");
}
}
/* Initialize a request object that is already constructed */
function initReq(reqType,url,bool){
/* Specify the function that will handle the HTTP response */
request.onreadystatechange=handleResponse;
request.open(reqType,url,bool);
request.send(null);
}


Blog Archive