C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Editing,deleting,sorting and paging in a datagrid


Posted Date: 04 Dec 2007    Resource Type: Code Snippets    Category: ASP.NET GridView
Author: rockyMember Level: Bronze    
Rating: Points: 10



This code performs basic functions in a gridview like editing deleting sorting and paging in gridview.....
I have used four fields in emp(table) database namely
1. id
2.empfirstname
3.emplastname
4.age



//The source file code lies below


<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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>Untitled Page</title>

<script language="javascript" type="text/javascript">
function check()
{

if(document.getElementById('<%=txtfirstname.ClientId%>').value=="")
{
alert('Please Enter first Name"');
document.getElementById('<%=txtfirstname.ClientId%>').focus();
return false;
}
if(document.getElementById('<%=txtlastname.ClientId%>').value=="")
{
alert('Please Enter lastname "');
document.getElementById('<%=txtlastname.ClientId%>').focus();
return false;
}

if(document.getElementById('<%=txtage.ClientId%>').value=="")
{
alert('Please Enter employee age"');
checknumber();

document.getElementById('<%=txtage.ClientId%>').focus();
return false;
}






}







</script>











</head>
<body>
<form id="form1" action="Default.aspx" method="post" onsubmit="return check(this)" runat="server">
<div>
<table id="tbl" border="2" align="center" cellpadding="0" cellspacing="2" style=" height: 100%" visible=true runat=server >

<tr bgcolor="#FFFFFF">
<td >
<asp:Label ID="txtfirstname" runat="server" Text="First Name" Width="246px" ForeColor="#C00000"></asp:Label></td>
<td> <asp:TextBox ID="txt" runat="server" Text=""></asp:TextBox>
</td>

</tr>
<tr>
<td >
<asp:Label ID="txtlastname" runat="server" Text="last Name" ForeColor="#C00000"></asp:Label></td>
<td> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox></td>

</tr>
<tr>
<td >
<asp:Label ID="txtage" runat="server" Text="Age" ForeColor="#C00000"></asp:Label></td>
<td>
<asp:TextBox ID="textbox2" runat="server"></asp:TextBox></td>
</tr>
</table>
<asp:HiddenField ID="hdn" runat="server" />

</div>
<table id=tbl1 align= center visible=true runat=server>
<tr>
<td>
<asp:Button id=btnSave align=center CommandName="Save" Text=Save runat=server />
<asp:Button ID="btnReset" align=center Text=Reset runat=server />
<asp:Button ID="btnCancel" align=center Text=Cancel runat=server />


</td>
</tr>
</table>
<table align=center style="width: 132px">
<tr>
<td>
<asp:Label ID=err visible=false runat=server>
</asp:Label>
</td>
</tr>
</table>
<table id=tbl3 align=right >


</table>


<asp:GridView ID="GridView1" width="100%" AllowSorting="true" AllowPaging="TRUE" runat="server" AutoGenerateColumns="false" BackColor="#FFE0C0" BorderColor="Blue" BorderStyle="Double" ForeColor="Maroon" PageSize="3" >
<Columns >
<asp:BoundField DataField="id" SortExpression ="id" HeaderText="Emp Id." >
<HeaderStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="empfname" HeaderText="First Name" SortExpression="empfname" >
<HeaderStyle Width="100px" />
</asp:BoundField>
<asp:BoundField DataField="emplastname" HeaderText="Last Name" SortExpression="emplastname">
<HeaderStyle Width="150px" />
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>

<asp:HyperLink ID="hyk" Text = "Edit" NavigateUrl='<%# Edit(DataBinder.Eval(Container, "DataItem.id")) %>' runat="server">
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>

<asp:HyperLink ID="hyk" Text = "Delete" NavigateUrl='<%# Del(DataBinder.Eval(Container, "DataItem.id")) %>' runat="server" >
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>


</Columns>


</asp:GridView>


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







The asp.vb code lies here..........!!!!!!!!!!


Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration

Partial Class _Default
Inherits System.Web.UI.Page
Public Shared uid As String
Dim mode As String
Dim flag As Boolean
Dim dv As DataView

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not IsPostBack Then
uid = Request.QueryString("uid")
mode = Request.QueryString("mode")
flag = True
Session("id") = uid
BindGrid()
Else

End If

If uid <> "" Then
btnSave.Text = "Update"
btnSave.CommandName = "Update"
Else
btnSave.Text = "Save"
btnSave.CommandName = "Save"
End If
If (mode = "D") Then
btnSave.Text = "Update"
DelRecord(uid)

ElseIf uid <> "" And flag = True Then
flag = False
BindRecord(uid)
tbl.Visible = True
tbl1.Visible = True
End If


btnSave.Attributes.Add("OnClick", "return check();")

End Sub

Public Sub BindGrid()
Dim Connstr As String
Connstr = "Server=dotnetrs; uid=sa; pwd=rahul; database=testingdatabase"
Dim conn As New SqlConnection(Connstr)
Dim strqry As String
strqry = "select id,empfname,emplastname from [TestingDataBase].[dbo].[emp]"
Dim ad As New SqlDataAdapter(strqry, conn)
Dim dt As New DataTable
ad.Fill(dt)
Session("datatable") = dt
dv = dt.DefaultView()
GridView1.DataSource = dv
GridView1.DataBind()
End Sub

Protected Function edit(ByRef id) As String

Return "default.aspx?uid=" & id
End Function
Protected Function del(ByRef id) As String
Return "default.aspx?uid=" & id & "&Mode=D"
End Function

Public Sub BindRecord(ByRef id)

Dim Connstr As String
Connstr = "Server=dotnetrs; uid=sa; pwd=rahul; database=testingdatabase"
Dim conn As New SqlConnection(Connstr)
Dim strqry As String

Dim dt As New DataTable
err.Visible = False
strqry = "select * from [TestingDataBase].[dbo].[emp] where id =@id"
Dim cmd As New SqlCommand(strqry, conn)
cmd.CommandType = CommandType.Text
cmd.Parameters.Add("@id", SqlDbType.Int).Value = id
Dim ad As New SqlDataAdapter(cmd)
ad.Fill(dt)
Dim dtrow As DataRow
If Not IsNothing(dt) Then

For Each dtrow In dt.Rows
txt.Text = dtrow("empfname")
TextBox1.Text = dtrow("emplastname")
textbox2.Text = dtrow("age")


Next
End If
End Sub

Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnSave.Click
Dim obj(3) As Object
obj(0) = txt.Text

obj(1) = TextBox1.Text
obj(2) = textbox2.Text
If btnSave.CommandName = "Save" Then
save(obj)
ElseIf btnSave.CommandName = "Update" Then
Update(obj)
End If


End Sub

Protected Sub Update(ByRef obj)
Dim Connstr As String
Connstr = "Server=dotnetrs; uid=sa; pwd=rahul; database=testingdatabase"
Dim conn As New SqlConnection(Connstr)
Dim strqry As String
Dim ad As New SqlDataAdapter


strqry = "update [TestingDataBase].[dbo].[emp] set empfname=@empfname,emplastname=@emplastname,age=@age where id=@id"
Dim cmd As New SqlCommand(strqry, conn)
cmd.Parameters.Add("@empfname", SqlDbType.VarChar).Value = obj(0)
cmd.Parameters.Add("@emplastname", SqlDbType.VarChar).Value = obj(1)
cmd.Parameters.Add("@age", SqlDbType.Int).Value = obj(2)
cmd.Parameters.Add("@id", SqlDbType.Int).Value = uid

conn.Open()
Dim ret As Integer = cmd.ExecuteNonQuery()
If (ret = 1) Then

err.Visible = True
err.Text = "Record has Been sucessfully updated"
BindGrid()
tbl.Visible = True
tbl1.Visible = True
reset()

Else
err.Visible = True
err.Text = "Error in saving"
BindGrid()
End If

End Sub
Protected Sub DelRecord(ByVal uid)
Dim Connstr As String
Connstr = "Server=dotnetrs; uid=sa; pwd=rahul; database=testingdatabase"
Dim conn As New SqlConnection(Connstr)
Dim strqry As String
Dim dt As New DataTable


strqry = "delete from [TestingDataBase].[dbo].[emp] where id = @id"
Dim cmd As New SqlCommand(strqry, conn)
cmd.CommandType = CommandType.Text
conn.Open()
cmd.Parameters.Add("@id", SqlDbType.Int).Value = uid
Dim ret As Integer = cmd.ExecuteNonQuery()
If (ret = 1) Then

err.Visible = True
err.Text = "Record is Deleted"
BindGrid()
btnSave.Text = "Save"
btnSave.CommandName = "Save"
mode = ""


Else
err.Visible = True
err.Text = "Error in Deletion"
BindGrid()
End If
End Sub


Protected Sub save(ByVal obj)
Dim Connstr As String
Connstr = "Server=dotnetrs; uid=sa; pwd=rahul; database=testingdatabase"
Dim conn As New SqlConnection(Connstr)
Dim strqry As String
Dim ad As New SqlDataAdapter


strqry = "insert into [TestingDataBase].[dbo].[emp] (empfname,emplastname,age) " & _
" values (@empfname,@emplastname,@age)"

Dim cmd As New SqlCommand(strqry, conn)
cmd.Parameters.Add("@empfname", SqlDbType.VarChar).Value = obj(0)
cmd.Parameters.Add("@emplastname", SqlDbType.VarChar).Value = obj(1)
cmd.Parameters.Add("@age", SqlDbType.VarChar).Value = obj(2)
conn.Open()
Dim ret As Integer = cmd.ExecuteNonQuery()
If (ret = 1) Then

err.Visible = True
err.Text = "Record updated"
tbl.Visible = True
tbl1.Visible = True
GridView1.Visible = True
BindGrid()
reset()
txt.Focus()
btnSave.CommandName = "Update"
Else
err.Visible = True
err.Text = "Error in saving"
BindGrid()
End If

End Sub

Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click
Response.Redirect("default.aspx")
End Sub

Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
txt.Text = ""
TextBox1.Text = ""
textbox2.Text = ""
err.Visible = False
End Sub
Public Sub reset()
err.Visible = False
txt.Text = ""
TextBox1.Text = ""
textbox2.Text = ""
btnSave.Text = "Save"

End Sub

Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
BindGrid()
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
End Sub

Protected Sub GridView1_SelectedIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSelectEventArgs) Handles GridView1.SelectedIndexChanging



End Sub

Protected Sub GridView1_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles GridView1.Sorting
If ViewState("direction") = Nothing Or ViewState("direction") = "Desc" Then
ViewState("direction") = "Asc"
Else
ViewState("direction") = "Desc"
End If

Dim dvDataView = New DataView(Session("datatable"))
dvDataView.Sort = e.SortExpression & " " & ViewState("direction")
GridView1.DataSource = dvDataView
GridView1.DataBind()
End Sub
End Class











Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sorting and paging  .  Editing  .  Deleting  .  Datagrid  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: How to kill Progress bar after running
Previous Resource: Show images in ASP.NET GridView control
Return to Discussion Resource Index
Post New Resource
Category: ASP.NET GridView


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design


Contact Us    Privacy Policy    Terms Of Use