Stored Procedures Are Precompiled So They Are Faster1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

Stored Procedures are precompiled so they are faster

Ask any one why he prefers stored procedures as compared to inline queries and most will reply
back with a standard statement:

“Stored procedures are precompiled and cached so the performance is much better.”

Let me just explain the above sentence more diagrammatically. When we fire SQL for the first
time, three things happen:

 The SQL syntax is checked for any errors.


 The best plan is selected to execute the SQL (choice to use clustered index, non-clustered
etc.).
 Finally the SQL is executed.

The above statement states that when you run a stored procedure for the first time it will go
through all the above steps and the plan will be cached in-memory. So the next time when the
stored procedure is executed it just takes the plan from the cache and executes the same. This
increases performance as the first two steps are completely eliminated.

The above statement also says / implies that for inline queries all the above steps are repeated
again and again which brings down the performance considerably.

The above explanation was pretty valid and true for older versions of SQL Server, but from 2005
onwards, all SQL statements, irrespective of it’s a SQL coming from inline code or stored
procedure or from anywhere else, they are compiled and cached.
Using Coalesce() in sqlserver

Introduction
When we have multi-value attribute with single or more null values in a Table, the Coalesce()
function is very useful.

Using the Code


If you consider the below facts placed in a employee table with Id, Name, ph_no, Alt_no,
Office no.

id Name Ph_ no Alt_ no Office no


101 Albert 999999 456453 321333
102 khan null null 123455
103 victor 112121 null null
104 lovely null null 1897321

The above Employee table may have single value or three values. If it has single value, then it
fills null values with remaining attributes.

When we retrieve the number from employee table, that number Should Not be Null value. To
get not null value from employee table, we use Coalesce() function. It returns the first
encountered Not Null Value from employee table.

Collapse | Copy Code

select id , name ,coalesce(Ph_no,Alt_no,Office_no) as contact number from


employee

It returns:

id Name Contactnumber
101 Albert 999999
102 khan 123455
103 victor 112121
104 lovely 1897321

Thank you!
<script type="text/javascript">

$(document).ready(function(){

if(getParameterByName('TopMenu') == 1)

$(".menu-con2").hide();

$(".icon-con").show();

$(".menu-con").show();

$("a.f-ag").removeClass("selected");

$(".logo-col").removeClass("logo-ag");

$("a.com-ser").addClass("selected");

if(getParameterByName('TopMenu') == 2)

$(".icon-con").hide();

$(".menu-con").hide();

$(".logo-col").addClass("logo-ag");;

$(".menu-con2").show();

$("a.com-ser").removeClass("selected");
$("a.f-ag").addClass("selected");

});

function getParameterByName(name) {

name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");

var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),

results = regex.exec(location.search);

return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));

</script>
Default.aspx: sorting example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"


Inherits="_Default" %>
<!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>Gridview Sorting</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvEmployee" runat="server" AutoGenerateColumns="false"
OnSorting="gvEmployee_Sorting" AllowSorting="true">
<HeaderStyle BackColor="#3E3E3E" Font-Bold="True" Font-Names="cambria"
ForeColor="White" />
<RowStyle Font-Names="Calibri" />
<Columns>
<asp:TemplateField HeaderText="Employee ID" SortExpression="empid">
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%#Eval("empid")%>'
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<asp:Label ID="lblName" runat="server" Text='<%#Eval("name")%>'
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation" SortExpression="designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server"
Text='<%#Eval("designation")%>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City" SortExpression="city">
<ItemTemplate>
<asp:Label ID="lblCity" runat="server" Text='<%#Eval("city")%>'
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" SortExpression="country">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server"
Text='<%#Eval("country")%>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

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


{
DataSet ds = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
ds.ReadXml(Server.MapPath("EmployeeDetails.xml"));
if (ds != null && ds.HasChanges())
{
gvEmployee.DataSource = ds;
gvEmployee.DataBind();
}
}
public SortDirection dir1
{
get
{
if (ViewState["dirstate"] == null)
{
ViewState["dirstate"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirstate"];
}
set
{
ViewState["dirstate"] = value;
}
}

public SortDirection dir


{
get
{
if (ViewState["dirState"] == null)
{
ViewState["dirState"] = SortDirection.Ascending;
}
return (SortDirection)ViewState["dirState"];
}
set
{
ViewState["dirState"] = value;
}
}

protected void gvEmployee_Sorting(object sender, GridViewSortEventArgs e)


{
BindData();
DataTable dt = new DataTable();
dt = ds.Tables[0];
{
string SortDir = string.Empty;
if (dir == SortDirection.Ascending)
{
dir = SortDirection.Descending;
SortDir = "Desc";
}
else
{
dir = SortDirection.Ascending;
SortDir = "Asc";
}
DataView sortedView = new DataView(dt);
sortedView.Sort = e.SortExpression + " " + SortDir;
gvEmployee.DataSource = sortedView;
gvEmployee.DataBind();
}
}
}
Default.aspx: insert, update using gridview

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs"


Inherits="Default2" %>

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


<head id="Head1" runat="server">
<title>Untitled Page</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="gvDetails" DataKeyNames="UserId,UserName" runat="server"
AutoGenerateColumns="false" CssClass="Gridview" HeaderStyle-BackColor="#61A6F8"
ShowFooter="true" HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="White"
onrowcancelingedit="gvDetails_RowCancelingEdit"
onrowdeleting="gvDetails_RowDeleting" onrowediting="gvDetails_RowEditing"
onrowupdating="gvDetails_RowUpdating"
onrowcommand="gvDetails_RowCommand">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server"
ImageUrl="~/Images/update.jpg" ToolTip="Update" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel"
ImageUrl="~/Images/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server"
ImageUrl="~/Images/Edit.png" ToolTip="Edit" Height="20px" Width="20px" />
<asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit"
runat="server" ImageUrl="~/Images/delete.png" ToolTip="Delete" Height="20px" Width="20px"
/>
</ItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="~/Images/AddNewitem.png"
CommandName="AddNew" Width="30px" Height="30px" ToolTip="Add new User"
ValidationGroup="validaiton" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<EditItemTemplate>
<asp:Label ID="lbleditusr" runat="server" Text='<%#Eval("Username") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblitemUsr" runat="server" Text='<%#Eval("UserName") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrusrname" runat="server"/>
<asp:RequiredFieldValidator ID="rfvusername" runat="server"
ControlToValidate="txtftrusrname" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="txtcity" runat="server" Text='<%#Eval("City") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblcity" runat="server" Text='<%#Eval("City") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrcity" runat="server"/>
<asp:RequiredFieldValidator ID="rfvcity" runat="server"
ControlToValidate="txtftrcity" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>

<asp:TemplateField HeaderText="Designation">
<EditItemTemplate>
<asp:TextBox ID="txtDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDesg" runat="server" Text='<%#Eval("Designation") %>'/>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtftrDesignation" runat="server"/>
<asp:RequiredFieldValidator ID="rfvdesignation" runat="server"
ControlToValidate="txtftrDesignation" Text="*" ValidationGroup="validaiton"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Label ID="lblresult" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

Default.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Drawing;
using System.Configuration;

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


{
SqlConnection con = new
SqlConnection(ConfigurationManager.ConnectionStrings["ApplicationServices1"].ConnectionSt
ring);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindEmployeeDetails();
}
}
protected void BindEmployeeDetails()
{
con.Open();
SqlCommand cmd = new SqlCommand("Select * from Employee_Details", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gvDetails.DataSource = ds;
gvDetails.DataBind();
}
else
{
ds.Tables[0].Rows.Add(ds.Tables[0].NewRow());
gvDetails.DataSource = ds;
gvDetails.DataBind();
int columncount = gvDetails.Rows[0].Cells.Count;
gvDetails.Rows[0].Cells.Clear();
gvDetails.Rows[0].Cells.Add(new TableCell());
gvDetails.Rows[0].Cells[0].ColumnSpan = columncount;
gvDetails.Rows[0].Cells[0].Text = "No Records Found";
}
}
protected void gvDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
gvDetails.EditIndex = e.NewEditIndex;
BindEmployeeDetails();
}
protected void gvDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Value.ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
TextBox txtcity = (TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtcity");
TextBox txtDesignation =
(TextBox)gvDetails.Rows[e.RowIndex].FindControl("txtDesg");
con.Open();
SqlCommand cmd = new SqlCommand("update Employee_Details set City='" +
txtcity.Text + "',Designation='" + txtDesignation.Text + "' where UserId=" + userid,
con);
cmd.ExecuteNonQuery();
con.Close();
lblresult.ForeColor = Color.Green;
lblresult.Text = username + " Details Updated successfully";
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowCancelingEdit(object sender, GridViewCancelEditEventArgs
e)
{
gvDetails.EditIndex = -1;
BindEmployeeDetails();
}
protected void gvDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userid =
Convert.ToInt32(gvDetails.DataKeys[e.RowIndex].Values["UserId"].ToString());
string username = gvDetails.DataKeys[e.RowIndex].Values["UserName"].ToString();
con.Open();
SqlCommand cmd = new SqlCommand("delete from Employee_Details where UserId=" +
userid, con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Red;
lblresult.Text = username + " details deleted successfully";
}
}
protected void gvDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtUsrname =
(TextBox)gvDetails.FooterRow.FindControl("txtftrusrname");
TextBox txtCity = (TextBox)gvDetails.FooterRow.FindControl("txtftrcity");
TextBox txtDesgnation =
(TextBox)gvDetails.FooterRow.FindControl("txtftrDesignation");
con.Open();
SqlCommand cmd =
new SqlCommand(
"insert into Employee_Details(UserName,City,Designation) values('" +
txtUsrname.Text + "','" +
txtCity.Text + "','" + txtDesgnation.Text + "')", con);
int result = cmd.ExecuteNonQuery();
con.Close();
if (result == 1)
{
BindEmployeeDetails();
lblresult.ForeColor = Color.Green;
lblresult.Text = txtUsrname.Text + " Details inserted successfully";
}
else
{
lblresult.ForeColor = Color.Red;
lblresult.Text = txtUsrname.Text + " Details not inserted";
}
}
}
}
Default3.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs"


Inherits="Default3" %>

<!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 id="Head1" runat="server">
<title>Sort Gridview Cloumns with Up and Down Arrows</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:11pt;
font-weight:normal;
color:black;
width:350px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvEmpDetails" runat="server" CssClass="Gridview"
AllowPaging="true" AllowSorting="true" PageSize="4" HeaderStyle-BackColor="#7779AF"
HeaderStyle-ForeColor="White" AutoGenerateColumns="false" ShowFooter="true"
DataSourceID="dsEmpdetails" onrowdatabound="gvEmpDetails_RowDataBound">
<PagerSettings Mode= "NumericFirstLast" FirstPageText="First"
PreviousPageText="Previous" NextPageText="Next" LastPageText="Last" />
<PagerStyle BackColor="#7779AF" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:BoundField DataField="EmpID" HeaderText="EmpID" SortExpression="EmpID" />
<asp:BoundField DataField="EmpName" HeaderText="EmpName" SortExpression="EmpName" />
<asp:BoundField DataField="Location" HeaderText="Location" SortExpression="Location"
/>
<asp:BoundField DataField="Amount" HeaderText="Amount" SortExpression="Amount" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="dsEmpdetails" runat="server"
ConnectionString="<%$ConnectionStrings:ApplicationServices1 %>"
SelectCommand="select * from EmployeeSalary" >
</asp:SqlDataSource>
</div>
</form>
</body>
</html>
Default3.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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


{
protected void Page_Load(object sender, EventArgs e)
{

protected void gvEmpDetails_RowDataBound(object sender, GridViewRowEventArgs e)


{
string imgAsc = @" <img src='AscArrow.jpg' border='0' title='Ascending' />";
string imgDes = @" <img src='DscArrow.jpg' border='0' title='Descendng' />";
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
LinkButton lnkbtn = (LinkButton)cell.Controls[0];
if (lnkbtn.Text == gvEmpDetails.SortExpression)
{
if (gvEmpDetails.SortDirection == SortDirection.Ascending)
{
lnkbtn.Text += imgAsc;
}
else
lnkbtn.Text += imgDes;
}
}
}
}
}
Default4.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default4.aspx.cs"


Inherits="Default4" %>

<!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 id="Head1" 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"
HeaderStyle-ForeColor="White" HeaderStyle-Font-Bold ="true" DataKeyNames="EmpID"
runat="server" ShowFooter="true" AllowPaging="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>
Default4.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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


{
int total = 0;
protected void gvEmp_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
total += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Amount"));
}
if (e.Row.RowType == DataControlRowType.Footer)
{
Label lblamount = (Label)e.Row.FindControl("lblTotal");
lblamount.Text = total.ToString();
Label lblamout = (Label)e.Row.FindControl("lblamount");
lblamout.Text = total.ToString();
}
}
}
Default5.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default5.aspx.cs"


Inherits="Default5" %>

<!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 id="Head1" runat="server">
<title>Gridview onmouseover and onmouseout</title>
<script type="text/javascript">
var oldgridcolor;
function SetMouseOver(element) {
oldgridcolor = element.style.backgroundColor;
element.style.backgroundColor = '#ffeb95';
element.style.cursor = 'pointer';
element.style.textDecoration = 'underline';
}
function SetMouseOut(element) {
element.style.backgroundColor = oldgridcolor;
element.style.textDecoration = 'none';
}

</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView runat="server" ID="gvrecords" AutoGenerateColumns="false"
onrowdatabound="gvrecords_RowDataBound">

<Columns>
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Email" HeaderText="Email" />
</Columns>

<columns>
<asp:boundfield headertext="ACount" datafield="ACount" />
<asp:boundfield headertext="BCount" datafield="BCount" />
<asp:boundfield headertext="DCount" datafield="DCount" />
<asp:templatefield headertext="Status">
<itemtemplate>
<asp:label id="aCount" runat="server" />
<asp:label id="bCount" runat="server" />
<asp:label id="dCount" runat="server" />
</itemtemplate>
</asp:templatefield>
</columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Default5.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;

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


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridview();
}
}
protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onmouseover"] = "javascript:SetMouseOver(this)";
e.Row.Attributes["onmouseout"] = "javascript:SetMouseOut(this)";
}
}
protected void BindGridview()
{
SqlConnection con =
new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial
Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserDetails", con);
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvrecords.DataSource = ds;
gvrecords.DataBind();
}
}
Default6.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default6.aspx.cs"


Inherits="Default6" %>

<!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 id="Head1" runat="server">
<title>Delete Rows in Gridview with Checkbox</title>
<style type="text/css">
.Gridview
{
font-family:Verdana;
font-size:10pt;
font-weight:normal;
color:black;
}
</style>

<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="gvUserDetails" runat="server" DataSourceID="objUsers"
DataKeyNames="UserId" CssClass="Gridview" AutoGenerateColumns="false"
HeaderStyle-BackColor="#61A6F8" HeaderStyle-Font-Bold="true"
HeaderStyle-ForeColor="White">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkdelete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UserName" HeaderText="UserName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName" />
<asp:BoundField DataField="Location" HeaderText="Location" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="objUsers" runat="server"
ConnectionString="<%$ConnectionStrings:dbconnection %>"
SelectCommand="select * from UserInformation"
DeleteCommand="delete from UserInformation where UserId=@UserId" >
<DeleteParameters>
<asp:Parameter Name="UserId" Type="Int32" />
</DeleteParameters>
</asp:SqlDataSource>
</div>
<asp:Button ID="btnDelete" runat="server" Text="Delete" onclick="btnDelete_Click" />
</form>
</body>
</html>

Default6.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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


{
protected void Page_Load(object sender, EventArgs e)
{
btnDelete.Attributes.Add("onclick", "javascript:return Confirmationbox()");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Loop through all the rows in gridview
foreach (GridViewRow gvrow in gvUserDetails.Rows)
{
CheckBox chkdelte = (CheckBox)gvrow.FindControl("chkdelete");
if (chkdelte.Checked)
{
int userid =
Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);
objUsers.DeleteParameters["UserId"].DefaultValue = userid.ToString();
objUsers.Delete();
}

//Finiding checkbox control in gridview for particular row


CheckBox chkdelete = (CheckBox)gvrow.FindControl("chkdelete");
//Condition to check checkbox selected or not
if (chkdelete.Checked)
{
//Getting UserId of particular row using datakey value
int usrid =
Convert.ToInt32(gvUserDetails.DataKeys[gvrow.RowIndex].Value);
objUsers.DeleteParameters["UserId"].DefaultValue = usrid.ToString();
objUsers.Delete();
}
}
}
}
Default7.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default7.aspx.cs"


Inherits="Default7" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:SqlDataSource ID="sourceProducts"
runat="server"
ConnectionString="<%$ ConnectionStrings:Northwind %>"
ProviderName="System.Data.SqlClient"
SelectCommand="SELECT ProductID, ProductName, UnitPrice,
UnitsInStock FROM Products">
</asp:SqlDataSource>
<asp:GridView ID="GridView1"
runat="server"
AutoGenerateColumns="False"
CellPadding="4"
DataKeyNames="ProductID"
DataSourceID="sourceProducts"
Font-Names="Verdana"
Font-Size="Small"
ForeColor="#333333"
GridLines="None"
AllowPaging="True"
OnRowCommand="GridView1_RowCommand">
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#FFFBD6" ForeColor="#333333" />
<PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center"
/>
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" runat="server"
ImageUrl='<%# GetStatusPicture(Container.DataItem)
%>'
CommandName="StatusClick"
CommandArgument='<%# Eval("ProductID") %>'
/></ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProductID"
HeaderText="ID"
InsertVisible="False"
ReadOnly="True"
SortExpression="ProductID" />
<asp:BoundField DataField="ProductName"
HeaderText="Product"
SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice"
DataFormatString="{0:C}"
HeaderText="Price"
SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock"
HeaderText="UnitsInStock"
SortExpression="Units In Stock" />
</Columns>
</asp:GridView>
<br />
<asp:Label ID="lblInfo" runat="server" Font-Names="Verdana" Font-
Size="Small"></asp:Label>

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

Default7.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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


{
protected string GetStatusPicture(object dataItem)
{
int units = Int32.Parse(DataBinder.Eval(dataItem, "UnitsInStock").ToString());
if (units == 0)
{
return "0.gif";
}
else if (units > 50)
{
return "50.gif";
}
else
{
return "blank.gif";
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "StatusClick")
lblInfo.Text = "You clicked product #" + e.CommandArgument;
}
}
Stored procedure:

USE [umbracodev_new]
GO
/****** Object: StoredProcedure [dbo].[UpdateNPEPaymentTransaction]
Script Date: 05/30/2014 15:05:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: IQR_RHR
-- Create date: 20101228
-- Description:
-- Update Date : 2014-02-12
-- Updated By : Hardik Pithadiya
-- Description : Added new field in Update Product Id
-- =============================================
ALTER PROCEDURE [dbo].[UpdateNPEPaymentTransaction]
-- Add the parameters for the stored procedure here
@UID uniqueidentifier OUTPUT,
@Status varchar(10) = null,
@MessageLog varchar(max) = null,
@CompletedOn datetime = null,
@XmlSerializedObjectResponse xml = null,
@ProductId VARCHAR(255) = NULL,
@ContactId INT = NULL,
@SplitTransactionID BIGINT = NULL,
@PaymentReferenceId VARCHAR(255) = NULL,
@TransactionTypeId INT = NULL,
@IsEmailNotificationSent BIT = NULL,
@CreditCardType VARCHAR(50) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

UPDATE [dbo].[NPEPaymentTransaction]
SET
[Status] = @Status
,[MessageLog] = @MessageLog
,[CompletedOn] = @CompletedOn

,[XmlSerializedObjectResponse]=COALESCE(@XmlSerializedObjectResponse,XmlSeria
lizedObjectResponse)
,[ProductId] = COALESCE(@ProductId,ProductId)
,[ContactId] = COALESCE(@ContactId, [ContactId])
,[PaymentTransactionId] =
COALESCE(@PaymentReferenceId,[PaymentTransactionId])
,[TransactionTypeId] =
COALESCE(@TransactionTypeId,TransactionTypeId)
,[SplitTransactionId] =
COALESCE(@SplitTransactionId,SplitTransactionId)
,[IsEmailNotificationSent] =
COALESCE(@IsEmailNotificationSent,IsEmailNotificationSent)
,[CreditCardType] = COALESCE(@CreditCardType,CreditCardType )
WHERE [UID] = @UID
END

USE [umbracodev_new]
GO
/****** Object: StoredProcedure [dbo].[GetNPEPaymentTransaction] Script
Date: 05/30/2014 15:31:30 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: IQR_RHR
-- Create date: 20101228
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[GetNPEPaymentTransaction]
-- Add the parameters for the stored procedure here
@UID uniqueidentifier
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here


SELECT [UID]
,[Description]
,[XmlSerializedObject]
,[XmlSerializedObjectResponse]
,[Amount]
,[PayPalAuthId]
,[Status]
,[OnSuccessRedirect]
,[MessageLog]
,[IP]
,[ProviderId]
,[CreatedOn]
,[AuthorizedOn]
,[CompletedOn]
,[CreatedBy]
,[IsRecurring]
,[RecurringStartDate]
,[RecurringFrequency]
,[TotalRecurringPayments]
,[OnCancelRedirect]
,[FirstName]
,[LastName]
,[AddressLine1]
,[AddressLine2]
,[City]
,[State]
,[Country]
,[Zip]
,[ProductId]
,[ContactId]
,[TransactionTypeId]
,[SplitTransactionId]
,[PaymentTransactionId]
,[CustomDataSetDetails]
,[IsEmailNotificationSent]
FROM [dbo].[NPEPaymentTransaction]
WHERE [UID] = @UID

END

USE [umbracodev_new]
GO
/****** Object: StoredProcedure [dbo].[SaveNPEPaymentTransaction] Script
Date: 05/30/2014 15:32:29 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: IQR_RHR
-- Create date: 20101228
-- Description:
-- =============================================
ALTER PROCEDURE [dbo].[SaveNPEPaymentTransaction]
-- Add the parameters for the stored procedure here
@UID uniqueidentifier OUTPUT,
@Description varchar(max) = null,
@XmlSerializedObject xml = null,
@Amount decimal(18,2) = null ,
@PayPalAuthId varchar(50) = null,
@Status varchar(10) = null,
@OnSuccessRedirect varchar(200) = null,
@MessageLog varchar(max) = null,
@IP varchar(50) = null,
@ProviderId int = null,
@AuthorizedOn datetime = null,
@CompletedOn datetime = null,
@CreatedBy varchar(200) = null,
@IsRecurring bit = null,
@RecurringStartDate datetime = null,
@RecurringFrequency int = null,
@TotalRecurringPayments int = null,
@OnCancelRedirect varchar(200)= null,
@FirstName nvarchar(max) = null,
@LastName nvarchar(max) = null,
@AddressLine1 nvarchar(max) = null,
@AddressLine2 nvarchar(max) = null,
@City nvarchar(max) = null,
@State nvarchar(max) = null,
@Country nvarchar(max) = null,
@Zip nvarchar(max) = null,
--inserted by Tushar Vaja for Get User Agent Information
@UserAgent varchar(200) = null,
@XmlSerializedObjectResponse xml = null,
@SplitTransactionId BIGINT = NULL,
@ContactID INT = NULL,
@PaymentTransactionId VARCHAR(255) = NULL,
@CustomDataSetDetails NVARCHAR(MAX) = NULL,
@CreditCardType VARCHAR(50) = NULL
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

--determine the mode


IF @UID IS NULL
BEGIN
SET @UID = NEWID()

INSERT INTO [dbo].[NPEPaymentTransaction]


([UID]
,[Description]
,[XmlSerializedObject]
,[Amount]
,[PayPalAuthId]
,[Status]
,[OnSuccessRedirect]
,[MessageLog]
,[IP]
,[ProviderId]
,[CreatedOn]
,[AuthorizedOn]
,[CompletedOn]
,[CreatedBy]
,[IsRecurring]
,[RecurringStartDate]
,[RecurringFrequency]
,[TotalRecurringPayments]
,[OnCancelRedirect]
,[FirstName]
,[LastName]
,[AddressLine1]
,[AddressLine2]
,[City]
,[State]
,[Country]
,[Zip]
,[UserAgent]
,[XmlSerializedObjectResponse]
,[SplitTransactionId]
,[ContactId]
,[PaymentTransactionId]
,[CustomDataSetDetails]
,[CreditCardType]
)
VALUES
(@UID
,@Description
,@XmlSerializedObject
,@Amount
,@PayPalAuthId
,@Status
,@OnSuccessRedirect
,@MessageLog
,@IP
,@ProviderId
,GETDATE()
,@AuthorizedOn
,@CompletedOn
,@CreatedBy
,@IsRecurring
,@RecurringStartDate
,@RecurringFrequency
,@TotalRecurringPayments
,@OnCancelRedirect
,@FirstName
,@LastName
,@AddressLine1
,@AddressLine2
,@City
,@State
,@Country
,@Zip
,@UserAgent
,@XmlSerializedObjectResponse
,@SplitTransactionId
,@ContactID
,@PaymentTransactionId
,@CustomDataSetDetails
,@CreditCardType
)
END
ELSE
BEGIN
UPDATE [dbo].[NPEPaymentTransaction]
SET
[PayPalAuthId] = @PayPalAuthId
,[Status] = @Status
,[MessageLog] = @MessageLog
,[AuthorizedOn] = @AuthorizedOn
,[CompletedOn] = @CompletedOn
,[CreditCardType]
=COALESCE(@CreditCardType,CreditCardType)
WHERE [UID] = @UID
END

END

You might also like