Академический Документы
Профессиональный Документы
Культура Документы
Procedure in ASP.Net
http://www.aspsnippets.com/Articles/GridView-CRUD-Select-Insert-Edit-UpdateDelete-using-Single-Stored-Procedure-in-ASPNet.aspx
Database
I have made use of the following table Customers with the schema as follows.
HTML Markup
The HTML Markup consists of an ASP.Net GridView with multiple event handlers assigned
which will be discussed later.
The GridView has a CommandField column which will display the command buttons i.e.
Edit, Update, Cancel and Delete.
Below the GridView theres a Form which will allow us to insert data to the SQL Server
database table.
The following stored procedure will be used to perform Select, Insert, Update and Delete
operations on the SQL Server database table.
CREATE PROCEDURE [dbo].[Customers_CRUD]
@Action VARCHAR(10)
,@CustomerId INT = NULL
,@Name VARCHAR(100) = NULL
,@Country VARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
--SELECT
IF @Action = 'SELECT'
BEGIN
SELECT CustomerId, Name, Country
FROM Customers
END
--INSERT
IF @Action = 'INSERT'
BEGIN
INSERT INTO Customers(Name, Country)
VALUES (@Name, @Country)
END
--UPDATE
IF @Action = 'UPDATE'
BEGIN
UPDATE Customers
SET Name = @Name, Country = @Country
WHERE CustomerId = @CustomerId
END
--DELETE
IF @Action = 'DELETE'
BEGIN
DELETE FROM Customers
WHERE CustomerId = @CustomerId
END
END
.aspx.cs page
Namespaces
You will need to import the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
OUTPUT
For the GridView I have set EmptyDataText to display message when no records are present.
When the Edit Button is clicked, the GridViews OnRowEditing event handler is triggered.
Here simply the EditIndex of the GridView is updated with the Row Index of the GridView
Row to be edited.
protected void OnRowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
this.BindGrid();
}
Update
When the Update Button is clicked, the GridViews OnRowUpdating event handler is
triggered.
CustomerId which is the primary key is fetched from the DataKey property of GridView while
the Name and Country fields are fetched from their respective TextBoxes and are passed to
the Stored Procedure with Action parameter value as UPDATE.
protected void OnRowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GridView1.Rows[e.RowIndex];
int customerId = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
string name = (row.FindControl("txtName") as TextBox).Text;
string country = (row.FindControl("txtCountry") as TextBox).Text;
string constr
= ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Customers_CRUD"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Action", "UPDATE");
cmd.Parameters.AddWithValue("@CustomerId", customerId);
cmd.Parameters.AddWithValue("@Name", name);
cmd.Parameters.AddWithValue("@Country", country);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
GridView1.EditIndex = -1; // //GridView has Indexes, 0 means edit mode, -1 means readonly mode
this.BindGrid(); // Once the gridview mode is changed to 0, we have to pull the data
}
Cancel Edit
When the Cancel Button is clicked, the GridViews OnRowCancelingEdit event handler is
triggered. Here the EditIndex is set to -1 and the GridView is populated with data.
protected void OnRowCancelingEdit(object sender, EventArgs e)
{
GridView1.EditIndex = -1;// Once Gridview Update is cancelled, then we have to set the index of GridView to
readonly mode.
this.BindGrid(); //reload
}
o/p
CONFIRM MESSAGE BOX :- when deleting row, I have made use of OnRowDataBound event
handler where I have first determined the Delete Button and then I have attach the
JavaScript Confirm to its client side Click event handler.
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex !=
GridView1.EditIndex)
{
(e.Row.Cells[2].Controls[2] as LinkButton).Attributes["onclick"] = "return
confirm('Do you want to delete this row?');";
N.B :- ((LinkButton)GridView1.Rows[0].Cells[0].Controls[0]).Text {complete with sini)
}
}
o/p
In this approach, Data is displayed in Grid with Edit and Delete options. There is also link to add New
record. When user clicks to add new item, the page is redirected to another page having different
controls with default values, instructions and validators. After entering data, when user submits form,
It is redirected to back on Grid page with new entry.
When user clicks on edit option of any record, It is redirected to page with filled form. Generally same
form is used with query-string parameter to retrieve data from database, fill form and to
differentiate add /edit operations.
This approach is useful when form has many fields and structure is complex.
2. Pop-Up Form:
3. Inline Editing:
In this approach, all operations are done in Grid. When user clicks on edit option, all items become
editable and on saving, again become read only.
http://techbrij.com/show-modal-popup-edit-aspdotnet-gridview
This article explains how to add a pop-up control to a gridview in order to display drill-down (Master
detail) information without using ajaxcontroltoolkit ModalPopup extender. let us take an example to
display Northwind databases customer table.
GridView Structure:
</asp:TemplateField>
</Columns>
</asp:GridView>
Popup Structure:
?
<style type="text/css">
#mask
{
position: fixed;
left: 0px;
top: 0px;
z-index: 4;
opacity: 0.4;
-ms-filter:
"progid:DXImageTransform.Microsoft.Alpha(Opacity=40)"; /* first!*/
filter: alpha(opacity=40); /* second!*/
background-color: gray;
display: none;
width: 100%;
height: 100%;
}
</style>
<script src="Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript" language="javascript">
function ShowPopup() {
$('#mask').show();
$('#<%=pnlpopup.ClientID %>').show();
}
function HidePopup() {
$('#mask').hide();
$('#<%=pnlpopup.ClientID %>').hide();
}
$(".btnClose").live('click',function () {
HidePopup();
});
</script>
<div id="mask">
</div>
<asp:Panel ID="pnlpopup" runat="server" BackColor="White" Height="175px"
Width="300px" Style="z-index:111;background-color: White; position:
absolute; left: 35%; top: 12%;
</td>
<td>
<asp:Label ID="lblID" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
Contact Name:
</td>
<td>
<asp:Label ID="lblContactName"
runat="server"></asp:Label>
</td>
</tr>
<tr>
<td align="right">
Address:
</td>
<td>
<asp:TextBox ID="txtAddress" runat="server" />
</td>
</tr>
<tr>
<td align="right">
City:
</td>
<td>
<asp:TextBox ID="txtCity" runat="server" />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button ID="btnUpdate" CommandName="Update"
runat="server" Text="Update" OnClick="btnUpdate_Click" />
<input type="button" class="btnClose" value="Cancel" />
</td>
</tr>
</table>
</asp:Panel>
Here mask div is used as a layer to block page elements and pnlpopup will be displayed as
popup.
GridViewData.DataKeys[gvrow.RowIndex].Value.ToString())[0];
lblContactName.Text =
HttpUtility.HtmlDecode(gvrow.Cells[2].Text);
txtAddress.Text = HttpUtility.HtmlDecode(gvrow.Cells[3].Text);
txtCity.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);
Popup(true);
}
}
Bind();
Popup(false);
}
}
//To show message after performing operations
void Popup(bool isDisplay)
{
StringBuilder builder = new StringBuilder();
if (isDisplay)
{
builder.Append("<script language=JavaScript> ShowPopup();
</script>\n");
Page.ClientScript.RegisterStartupScript(this.GetType(),
"ShowPopup", builder.ToString());
}
else
{
builder.Append("<script language=JavaScript> HidePopup();
</script>\n");
Page.ClientScript.RegisterStartupScript(this.GetType(),
"HidePopup", builder.ToString());
}
}
lbl.Text = (dt2.Year-dt1.Year).ToString();
}
else
{
}
But if you require month and date as well
Displaying Total in ASP.NET Gridview Footer Row Without using Template Field(using Enum)
There are tons of articles to display total in asp.net gridview footer row. The common approach to
implement this is:
1. Create template field of the column which is to be totalled.
2. Define FooterTemplate and add Label control.
3. Take a variable and add value of each row in GridView1_RowDataBound event.
4. Find label control in footer and assign the variable.
Its too complex. Lets see how to take advantage of LINQ or Lambda expression and skip these steps.
Namespaces
You will need to import the following namespaces
using System.Data;
using System.Drawing;
dt.Rows.Add("Hat", 90);
dt.Rows.Add("Scarf", 290);
dt.Rows.Add("Belt", 150);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
N.B:- Intrvw Questn :-
Bind gridview with value that doesnt saved in the database. (ans above)
Quantity Range
0
1 - 50
51 - 100
Background Color
RED
YELLOW
ORANGE
Here I will explain how to bind data to dropdownlist in gridview in asp.net using dataset
or populatedropdownlist in gridview in asp.net using dataset. we can bind dropdownlist in gridview
using ItemTemplate field.
To implement this concept first design tables in your database as explained in this
post populate dropdown based on another dropdown in asp.net . After that design your aspx page
like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Asp.net Bind Data to Dropdownlist in inside of gridview</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvUserInfo" runat="server" AutoGenerateColumns="false"OnRowDataBound="gvUserInf
o_RowDataBound" >
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="CountryId" HeaderText="CountryId" />
<asp:BoundField DataField="CountryName" HeaderText="CountryName" />
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:DropDownList ID="ddlCity" runat="server" Width="100px"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
C# Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
After that add following code in code behind
O/ p
delete multiple rows in gridview using checkbox in asp.net in c# , vb.net with confirmation
message or delete multiple rows or records from gridview using checkbox selection with
confirmation in asp.net using c#
first design one table UserDetails in your database as shown below
Column Name
Data Type
Allow Nulls
UserId
Int(IDENTITY=TRUE)
Yes
UserName
varchar(50)
Yes
FirstName
varchar(50)
Yes
LastName
varchar(50)
Yes
Once table created in database enter some dummy data to test application after that write the following code in
your aspx page
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>how to delete Multiple Rows from gridview in asp.net using checkbox</title>
<script type="text/javascript">
function Confirmationbox() {
var result = confirm('Are you sure you want to delete selected User(s)?');
if (result) {
return true;
}
else {
return false;
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5"runa
t="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="FirstName" DataField="FirstName" />
<asp:BoundField HeaderText="LastName" DataField="LastName" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnDelete" Text="Delete Selected Records" runat="server" FontBold="true"OnClientClick="javascript:return Confirmationbox();" onclick="btnDelete_Click" />
</div>
</form>
</body>
</html>
Now open code behind file and write the following code
C# Code
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class DeleteGridviewRows : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindUserDetails();
}
}
protected void BindUserDetails()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial
Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from UserDetails", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Close();
}
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvrow in gvDetails.Rows)
{
//Finiding checkbox control in gridview for particular row
CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkSelect");
//Condition to check checkbox selected or not
if (chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid = Convert.ToInt32(gvDetails.DataKeys[gvrow.RowIndex].Value);
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial
Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("delete from UserDetails where UserId=" + usrid, con);
cmd.ExecuteNonQuery();
con.Close();
}
}
}
BindUserDetails();
}
}
O/P
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Export Data to Excel from datatable or gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnExport" runat="server" Text="Export to Excel from Gridview"
onclick="btnExport_Click" />
<asp:Button ID="btnExportTable" runat="server" Text="Export to Excel from Datatable"
onclick="btnExportTable_Click" />
</form>
</body>
</html>
Now in code behind we need to write the code as like shown below
C#.NET Code
using System;
using System.Data;
using System.IO;
using System.Web.UI;
public partial class ExportExceldatatoDatatable : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gvDetails.DataSource = BindDatatable();
gvDetails.DataBind();
}
}
protected DataTable BindDatatable()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
dt.Rows.Add(1, "SureshDasari", "B.Tech", "Chennai");
dt.Rows.Add(2, "MadhavSai", "MBA", "Nagpur");
dt.Rows.Add(3, "MaheshDasari", "B.Tech", "Nuzividu");
dt.Rows.Add(4, "Rohini", "MSC", "Chennai");
dt.Rows.Add(5, "Mahendra", "CA", "Guntur");
dt.Rows.Add(6, "Honey", "B.Tech", "Nagpur");
return dt;
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
// Export data to Excel from Gridview
protected void btnExport_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;
filename={0}","Customers.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gvDetails.AllowPaging = false;
gvDetails.DataSource = BindDatatable();
gvDetails.DataBind();
//Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF");
//Applying stlye to gridview header cells
for (int i = 0; i < gvDetails.HeaderRow.Cells.Count; i++)
{
gvDetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015");
}
gvDetails.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
//Export data to excel from datatable
protected void btnExportTable_Click(object sender, EventArgs e)
{
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", string.Format("attachment;
filename={0}","Customers.xls"));
Response.ContentType = "application/ms-excel";
DataTable dt = BindDatatable();
string str = string.Empty;
foreach (DataColumn dtcol in dt.Columns)
{
Response.Write(str + dtcol.ColumnName);
str = "\t";
}
Response.Write("\n");
foreach (DataRow dr in dt.Rows)
{
str = "";
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write(str + Convert.ToString(dr[j]));
str = "\t";
}
Response.Write("\n");
}
Response.End();
}
}
N.B :-If you observe above code I added one function that is VerifyRenderingInServerForm this function is used
to avoid the error like control must be placed in inside of form tag. If we set
VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our
functionality will work perfectly.
O/P
GridView Sorting
http://www.dotnetinterviewquestions.in/article_aspnet-interview-questions:-can-you-explain-method-of-sortinggridviewcontrol-in-aspnet_4.html
Sorting: - Sorting allow you to sort the GridViewcontrol data in Ascending or Descending order.
Let's
In
demonstrate
order
to
simple
sort
the
example
GridView
to
see
how
control
you
exactly
we
need
can
to
sort
follow
the
GridView
Control.
the
following
steps.
Step1: - Create a new Project > Go to file > New > Project > ASP.NET Empty Web Application.
Now,
Add
Web
Form
in
to
your
application.
Go to Solution explorer > Right click on the project name> Select Add > Add New Item > Select Web Form and click Add.
Step2: -Now on the WebForm1 design modes just drag and drop GridView control from the ToolBox.
In the above diagram of GridView Control you see that the circled column is inblack color, now just go to properties of GridView control
set AllowSorting to true and also set AutoGenerateColumns to false.
As soon as you set Allowsorting to true will find the GridView control like below diagram.
In the above diagram you see that now the color of the circle columns is in blue color with underline on it this indicates that you can now sort
the
GridView
control.
Step3: -Go to source of the page and add the following in to it.
In the above code snippet you can see that I have called GridView1_Sorting event on OnSorting property and in the
columnBoundField just have allow SortExpression on StudentName column.
Once
you
have
done
with
the
above
steps
now
run
your
application
and
will
see
output
like
below
diagram.
The result above is displayed according to the data in theSQLServer table, now just click on StudentName and will find result like below
diagram.
Now, you can see that GridViewdata has been sorted in Descending order and if you again click on StudentName now the data will be sorted
in Ascending order.
In this Article, I am explaining how to make use JavaScript in the ASP.Net GridView control
and make it more elegant by reducing postbacks.
Functions such as
1. Highlighting selected row
2. Check/Uncheck all records using single checkbox.
3. Highlight row on mouseover event.
The above three functions can be easily achieved using JavaScript thus avoiding postbacks.
Basic Concept
The basic concept behind this is when the GridView is rendered on the client machine it is
rendered as a simple HTML table. Hence what the JavaScript will see a HTML table and not
the ASP.Net GridView control.
Hence once can easily write scripts for GridView, DataGrid and other controls once you know
how they are rendered.
To start with I have a GridView control with a header checkbox and checkbox for each
individual record
<asp:GridView ID="GridView1" runat="server" HeaderStyle-CssClass = "header"
AutoGenerateColumns = "false" Font-Names = "Arial"
OnRowDataBound = "RowDataBound"
Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="checkAll" runat="server" onclick = "checkAll(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" onclick = "Check_Click(this)" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px"
<asp:BoundField ItemStyle-Width="150px"
HeaderText="City" />
<asp:BoundField ItemStyle-Width="150px"
HeaderText="Country"/>
<asp:BoundField ItemStyle-Width="150px"
</Columns>
</asp:GridView>
Above you will notice I am calling two JavaScript functions checkAll and Check_Click which I have explained later.
Also I have attached a RowDataBound event to the GridView to add mouseover event
}
}
headerCheckBox.checked = checked;
}
</script>
The above function is invoked when you check / uncheck a checkbox in GridView row
First part of the function highlights the row if the checkbox is checked else it changes the
row to the original color if the checkbox is unchecked.
The Second part loops through all the checkboxes to find out whether at least one checkbox
is unchecked or not.
If at least one checkbox is unchecked it will uncheck the Header checkbox else it will check it
Check all checkboxes functionality
<script type = "text/javascript">
function checkAll(objRef)
{
var GridView = objRef.parentNode.parentNode.parentNode;
var inputList = GridView.getElementsByTagName("input");
for (var i=0;i<inputList.length;i++)
{
//Get the Cell To find out ColumnIndex
var row = inputList[i].parentNode.parentNode;
if(inputList[i].type == "checkbox" && objRef != inputList[i])
{
if (objRef.checked)
{
//If the header checkbox is checked
//check all checkboxes
//and highlight all rows
row.style.backgroundColor = "aqua";
inputList[i].checked=true;
}
else
{
//If the header checkbox is checked
//uncheck all checkboxes
//and change rowcolor back to original
if(row.rowIndex % 2 == 0)
{
//Alternating Row Color
row.style.backgroundColor = "#C2D69B";
}
else
{
row.style.backgroundColor = "white";
}
inputList[i].checked=false;
}
}
}
}
</script>
The above function is executed when you click the Header check all checkbox When the
Header checkbox is checked it highlights all the rows and checks the checkboxes in all rows.
And when unchecked it restores back the original color of the row and unchecks the
checkboxes.
Note:
The check all checkboxes checks all the checkboxes only for the current page of the
GridView and not all.
Highlight GridView row on mouseover event
<script type = "text/javascript">
function MouseEvents(objRef, evt)
{
var checkbox = objRef.getElementsByTagName("input")[0];
if (evt.type == "mouseover")
{
objRef.style.backgroundColor = "orange";
}
else
{
if (checkbox.checked)
{
objRef.style.backgroundColor = "aqua";
}
else if(evt.type == "mouseout")
{
if(objRef.rowIndex % 2 == 0)
{
//Alternating Row Color
objRef.style.backgroundColor = "#C2D69B";
}
else
{
objRef.style.backgroundColor = "white";
}
}
}
}
</script>
The above JavaScript function accepts the reference of the GridView Row and the event
which has triggered it.
Then based on the event type if event is mouseover it highlights the row by changing its
color to orange else if the event is mouseout it changes the rows color back to its original
before the event occurred.
The above function is called on the mouseover and mouseout events of the GridView row.
These events are attached to the GridView Row on the RowDataBound events refer the code
below
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow )
{
e.Row.Attributes.Add("onmouseover","MouseEvents(this, event)");
e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");
}
}
o/p
The following properties of the GridView come into play when Paging needs to be added.
1. PageSize - Sets the Size of the Page for GridView control
2. PageIndexChanging The event that will be triggered when the page link is clicked by the user.
DataTable dt = GetData(cmd);
GridView1.DataSource=dt;
GridView1.DataBind();
}
And now in order make the paging functionality work we will need to add the OnPageIndexChanging event of the
GridView control
protected void OnPaging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
As you can see above I am assigning a new Page index to the GridView and the rebinding the GridView control.
The figure below displays the GridView with Paging enabled.
CheckAllWasChecked = true;
}
}
The next snippet loops through the GridView rows and checks if the checkbox for that corresponding row is checked.
If the checkbox is checked its position is calculated using the following formula
CheckBoxIndex = GridView1.PageSize * GridView1.PageIndex + (RowIndex + 1)
The above formula gives the checkbox. RowIndex and PageIndex are zero based indexes i.e the first row or first
page starts from 0.
If the checkbox is checked its CheckBoxIndex added to the ArrayList else if it is already present and the checkbox is
not checked it is removed.
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
{
CheckBox chk =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBoxIndex = GridView1.PageSize * GridView1.PageIndex + (i + 1);
if (chk.Checked)
{
if (CheckBoxArray.IndexOf(CheckBoxIndex) == -1
&& !CheckAllWasChecked)
{
CheckBoxArray.Add(CheckBoxIndex);
}
}
else
{
if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1
|| CheckAllWasChecked)
{
CheckBoxArray.Remove(CheckBoxIndex);
}
}
}
}
The complete snippet is given below.
if (IsPostBack)
{
int CheckBoxIndex;
bool CheckAllWasChecked=false;
CheckBox chkAll =
(CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkAll");
string checkAllIndex = "chkAll-" + GridView1.PageIndex;
if (chkAll.Checked)
{
if (CheckBoxArray.IndexOf(checkAllIndex) == -1)
{
CheckBoxArray.Add(checkAllIndex);
}
}
else
{
if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
{
CheckBoxArray.Remove(checkAllIndex);
CheckAllWasChecked = true;
}
}
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
{
CheckBox chk =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
CheckBoxIndex=GridView1.PageSize*GridView1.PageIndex + (i + 1);
if (chk.Checked)
{
if (CheckBoxArray.IndexOf(CheckBoxIndex) == -1
&& !CheckAllWasChecked)
{
CheckBoxArray.Add(CheckBoxIndex);
}
}
else
{
if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1
|| CheckAllWasChecked)
{
CheckBoxArray.Remove(CheckBoxIndex);
}
}
}
}
}
Once this is done the ArrayList is saved to the ViewState.
ViewState["CheckBoxArray"] = CheckBoxArray;
Now in the GridView Paging Event you will need to recheck the checkboxes that are present in the ArrayList that we
saved in the ViewState. If the Check All checkbox is checked for that page index it will check all the checkboxes.
While checking through the checkboxes it also applies the background color to all checkboxes that are checked.
ArrayList CheckBoxArray = (ArrayList)ViewState["CheckBoxArray"];
string checkAllIndex = "chkAll-" + GridView1.PageIndex;
if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
{
CheckBox chkAll =
(CheckBox)GridView1.HeaderRow.Cells[0].FindControl("chkAll");
chkAll.Checked = true;
}
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
{
if (CheckBoxArray.IndexOf(checkAllIndex) != -1)
{
CheckBox chk =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
chk.Checked = true;
GridView1.Rows[i].Attributes.Add("style","background-color:aqua");
}
else
{
int CheckBoxIndex =GridView1.PageSize*(GridView1.PageIndex)+(i + 1);
if (CheckBoxArray.IndexOf(CheckBoxIndex) != -1)
{
CheckBox chk =
(CheckBox)GridView1.Rows[i].Cells[0].FindControl("CheckBox1");
chk.Checked = true;
GridView1.Rows[i].Attributes.Add("style", "background-color:aqua");
}
}
}
ColumnName
EmpID
EmpName
Location
Amount
DataType
Int(set identity property=true)
varchar(50)
varchar(50)
varchar(50)
After completion table creation enter some dummy and design your aspx page like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Show gridview Rows Total in </title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvEmp" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8" HeaderStyleForeColor="White" HeaderStyle-Font-Bold ="true" DataKeyNames="EmpID" runat="server"ShowFooter="true" Allo
wPaging="true" PageSize="5" AutoGenerateColumns="false" DataSourceID="sqldsEmp" onrowdatabound="gvEmp
_RowDataBound">
<FooterStyle Font-Bold="true" BackColor="#61A6F8" ForeColor="black" />
<Columns>
<asp:BoundField DataField="EmpID" HeaderText="Emp ID" />
<asp:BoundField DataField="EmpName" HeaderText="Emp Name" />
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:Label ID="lblLocation" runat="server" Text='<%#Eval("Location") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lbltxttotal" runat="server" Text="Total Amount"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblamount" runat="server" Text='<%# Eval("Amount") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="sqldsEmp" runat="server" SelectCommand="select * from
EmployeeSalary"ConnectionString="<%$ ConnectionStrings:dbconnection %>">
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
After that set your database connection in web.config like this because we are using this connection
in our sqldatasource to get the data from database
<connectionStrings>
<add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial
Catalog=MySampleDB"/>
</connectionStrings >