a complete sample: gridview callbacks sorting, paging and editing

gridview.aspx:

<%@ Page Language=”C#” AutoEventWireup=”false” EnableEventValidation=”true” CodeFile=”GridView.aspx.cs”
Inherits=”_Default” %>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”&gt;
<html xmlns=”http://www.w3.org/1999/xhtml”&gt;
<head id=”Head1″ runat=”server”>
<title>Untitled Page</title>

<script language=”javascript”>

function SortGrid(column)
{
var sort=””;
sort = document.getElementById(‘HFsort’).value;
if ( sort==”asc”) document.getElementById(‘HFsort’).value = “desc”; else document.getElementById(‘HFsort’).value =”asc”;

column=column+”|”+document.getElementById(‘HFsort’).value ;

<%= ClientScript.GetCallbackEventReference(this, “column”, “ShowResult”, null) %>;
}

function Pager(page)
{
<%= ClientScript.GetCallbackEventReference(this, “page”, “ShowResult”, null) %>;
}

function ShowResult(val, ctx)
{
document.getElementById(‘gv’).innerHTML = val;
}
</script>

<script type=”text/javascript”>
function CallServer(str)
{
var product = str;
<%= ClientScript.GetCallbackEventReference(this, “product”, “ReceiveServerData”,null)%>;
}

function ReceiveServerData(rValue)
{
document.getElementById(‘gv’).innerHTML = rValue;
}

</script>

</head>
<body>
<form id=”form1″ runat=”server”>
<div id=’gv’>
<asp:GridView ID=”GridView1″ runat=”server” AutoGenerateColumns=”False” DataSourceID=”SqlDataSource1″
OnRowDataBound=”GridView1_RowDataBound” OnRowUpdating=”GridView1_RowUpdating”
Style=”font-family: Arial” BackColor=”White” BorderColor=”#E7E7FF” BorderStyle=”None”
BorderWidth=”1px” CellPadding=”3″ GridLines=”Horizontal” AllowPaging=”True” AllowSorting=”True”
EnableViewState=”False” OnRowCreated=”GridView1_RowCreated” DataKeyNames=”countryid”
PageSize=”3″>
<FooterStyle BackColor=”#B5C7DE” ForeColor=”#4A3C8C” />
<RowStyle BackColor=”#E7E7FF” ForeColor=”#4A3C8C” />
<Columns>
<asp:TemplateField ShowHeader=”False”>
<EditItemTemplate>
<asp:LinkButton ID=”LinkButtonUpdate” runat=”server” CausesValidation=”True” CommandName=”Update”
Text=”update”></asp:LinkButton>
<asp:LinkButton ID=”LinkButtonCancel” runat=”server” CausesValidation=”False” CommandName=”Cancel”
Text=”cancel”></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID=”LinkButtonEdit” runat=”server” CausesValidation=”False” CommandName=”Edit”
Text=”edit”></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField=”countryid” HeaderText=”countryid” InsertVisible=”False”
ReadOnly=”True” SortExpression=”countryid” />
<asp:BoundField DataField=”countryname” HeaderText=”countryname” SortExpression=”countryname” />
</Columns>
<PagerStyle BackColor=”#E7E7FF” ForeColor=”#4A3C8C” HorizontalAlign=”Right” />
<SelectedRowStyle BackColor=”#738A9C” Font-Bold=”True” ForeColor=”#F7F7F7″ />
<HeaderStyle BackColor=”#4A3C8C” Font-Bold=”True” ForeColor=”#F7F7F7″ />
<AlternatingRowStyle BackColor=”#F7F7F7″ />
</asp:GridView>
</div>
<asp:HiddenField ID=”HFsort” runat=”server” Value=”asc” />
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” ConnectionString=”<%$ ConnectionStrings:tttConnectionString %>”
DeleteCommand=”DELETE FROM [country] WHERE [countryid] = @original_countryid AND [countryname] = @original_countryname”
InsertCommand=”INSERT INTO [country] ([countryname]) VALUES (@countryname)” SelectCommand=”SELECT * FROM [country]”
UpdateCommand=”UPDATE [country] SET [countryname] = @countryname WHERE [countryid] = @original_countryid AND [countryname] = @original_countryname”
ConflictDetection=”CompareAllValues” OldValuesParameterFormatString=”original_{0}”>
<DeleteParameters>
<asp:Parameter Name=”original_countryid” Type=”Int32″ />
<asp:Parameter Name=”original_countryname” Type=”String” />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name=”countryname” Type=”String” />
<asp:Parameter Name=”original_countryid” Type=”Int32″ />
<asp:Parameter Name=”original_countryname” Type=”String” />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name=”countryname” Type=”String” />
</InsertParameters>
</asp:SqlDataSource>
</form>

codebehind: gridview.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;

public partial class _Default : System.Web.UI.Page, ICallbackEventHandler
{

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

#region ICallbackEventHandler

public string GetCallbackResult()
{
StringWriter sr = new StringWriter();
HtmlTextWriter htm = new HtmlTextWriter(sr);
this.GridView1.RenderControl(htm);
htm.Close();
sr.Close();
return sr.ToString();
}

public void RaiseCallbackEvent(string eventArgument)
{

string[] command = eventArgument.Split(new char[] { ‘,’ });
string work = command[0];
if (work == “Edit”)
{
this.GridView1.EditIndex = Convert.ToInt32(command[1]);

}
else if (work == “Update”)
{

}
else if (work == “Cancel”)
{

}
else
{
if (work.Split(new char[] { ‘|’ })[0] == “page”)
{
GridView1.PageIndex = int.Parse((work.Split(new char[] { ‘|’ })[1])) -1;
}
else
{
if (work.Split(new char[] { ‘|’ })[1] == “asc”)
{
this.GridView1.Sort(work.Split(new char[] { ‘|’ })[0], SortDirection.Descending);
}
else
{
this.GridView1.Sort(work.Split(new char[] { ‘|’ })[0], SortDirection.Ascending);
}
}
}
this.GridView1.DataBind();

}

#endregion

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row != null && e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
if (cell.HasControls())
{
LinkButton button = cell.Controls[0] as LinkButton;
if (button != null)
{
if (GridView1.SortExpression == button.CommandArgument)
{
Image image = new Image();
if (GridView1.SortDirection == SortDirection.Ascending)
image.ImageUrl = “arrow_down.gif”;
else
image.ImageUrl = “arrow_up.gif”;
cell.Controls.Add(image);
}
}
}
}
}
}

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
{
foreach (TableCell cell in e.Row.Cells)
{
if (cell.HasControls())
{
LinkButton button = cell.Controls[0] as LinkButton;
if (button != null)
{
button.Attributes.Add(“onclick”, “SortGrid(‘” + button.Text + “‘); return false;”);
}
}
}
}

else if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton btnEdit = e.Row.FindControl(“LinkButtonEdit”) as LinkButton;
if (btnEdit != null) btnEdit.Attributes.Add(“onclick”, “CallServer(‘Edit,” + e.Row.RowIndex + “‘); return false;”);
LinkButton btnUpdate = e.Row.FindControl(“LinkButtonUpdate”) as LinkButton;
if (btnUpdate != null) btnUpdate.Attributes.Add(“onclick”, “CallServer(‘Update,” + e.Row.RowIndex + “‘); return false;”);
LinkButton btnCancel = e.Row.FindControl(“LinkButtonCancel”) as LinkButton;
if (btnCancel != null) btnCancel.Attributes.Add(“onclick”, “CallServer(‘Cancel,” + e.Row.RowIndex + “‘); return false;”);

}
else if (e.Row.RowType == DataControlRowType.Pager)
{

TableRow myrow = (TableRow)e.Row.Cells[0].Controls[0].Controls[0];

foreach (TableCell cell in myrow.Cells)
{
if (cell.HasControls())
{
LinkButton button = cell.Controls[0] as LinkButton;
if (button != null)
{
button.Attributes.Add(“onclick”, “Pager(‘page|” + button.Text + “‘); return false;”);
}
}
}
}
}
}

..:: Whereever you go, stay in touch. Download toolbar now! It´s free, private and secure. ::..

Advertisements

2 responses to “a complete sample: gridview callbacks sorting, paging and editing

  1. Pingback: GridView | ramprasadm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s