--------------------------
----------
C# Code----------------------
----------
-
using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.QuickStart;
using Telerik.QuickStart.Grid;
using Telerik.WebControls;
namespace Telerik.GridExamplesCSharp
.AJAX.Edit
OnDblClick
{
public abstract class DefaultCS : XhtmlPage
{
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.RadGrid1.NeedDataSour
ce += new Telerik.WebControls.GridNe
edDataSour
ceEventHan
dler(this.
RadGrid1_N
eedDataSou
rce);
this.RadGrid1.ColumnCreate
d += new Telerik.WebControls.GridCo
lumnCreate
dEventHand
ler(this.R
adGrid1_Co
lumnCreate
d);
this.Load += new EventHandler(this.Page_Loa
d);
}
#endregion
protected System.Web.UI.WebControls.
Label Label1;
protected Telerik.WebControls.RadGri
d RadGrid1;
protected void Page_Load(object sender, System.EventArgs e)
{
string clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '';", this.Label1.ClientID);
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
}
private void RadGrid1_NeedDataSource(ob
ject source, Telerik.WebControls.GridNe
edDataSour
ceEventArg
s e)
{
RadGrid1.DataSource = OrderDetails;
}
private DataTable OrderDetails
{
get
{
if (this.Session["OrderDetail
s"] != null)
{
return (DataTable)this.Session["O
rderDetail
s"];
}
DataTable res = DataSourceHelperCS.GetData
Table("SEL
ECT * FROM [Order Details]");
this.Session["OrderDetails
"] = res;
return res;
}
}
protected override void RaisePostBackEvent(IPostBa
ckEventHan
dler sourceControl, string eventArgument)
{
base.RaisePostBackEvent(so
urceContro
l, eventArgument);
if (sourceControl is RadGrid)
{
string[] postBackEventArgumentData = eventArgument.Split(':');
switch (postBackEventArgumentData
[0])
{
case "Edit":
{
((RadGrid1.MasterTableView
.Controls[
0] as Table).Rows[int.Parse(post
BackEventA
rgumentDat
a[1])] as GridItem).Edit = true;
RadGrid1.Rebind();
break;
}
case "Update":
{
GridItem item = ((RadGrid1.MasterTableView
.Controls[
0] as Table).Rows[int.Parse(post
BackEventA
rgumentDat
a[1])] as GridItem);
UpdateItem(item);
item.Edit = false;
RadGrid1.Rebind();
break;
}
}
}
}
private void RadGrid1_ColumnCreated(obj
ect sender, Telerik.WebControls.GridCo
lumnCreate
dEventArgs
e)
{
if (e.Column is GridBoundColumn)
{
if ((e.Column as GridBoundColumn).DataField
== "OrderID" || (e.Column as GridBoundColumn).DataField
== "ProductID")
{
(e.Column as GridBoundColumn).ReadOnly = true;
e.Column.HeaderStyle.Width
= Unit.Pixel(60);
}
else
{
e.Column.HeaderStyle.Width
= Unit.Pixel(150);
}
}
}
private void UpdateItem(GridItem item)
{
GridEditableItem editedItem = item as GridEditableItem;
DataTable ordersTable = this.OrderDetails;
//Locate the changed row in the DataSource
DataRow[] changedRows = ordersTable.Select( "OrderID = " + editedItem["OrderID"].Text
+ " AND " + " ProductID = " + editedItem["ProductID"].Te
xt );
string labelID = this.Label1.ClientID;
string clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';", labelID, "");
if (changedRows.Length != 1)
{
clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';",
labelID, "Unbale to locate the Order for updating.");
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
//The GridTableView will fill the values from all editable columns in the hash
item.OwnerTableView.Extrac
tValuesFro
mItem(newV
alues, editedItem);
DataRow changedRow = changedRows[0];
changedRow.BeginEdit();
try
{
foreach( DictionaryEntry entry in newValues )
{
changedRow[(string)entry.K
ey] = entry.Value;
}
changedRow.EndEdit();
}
catch( Exception ex )
{
changedRow.CancelEdit();
//In AJAX mode this will update the corresponding label text, client-side:
clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';",
labelID, Server.HtmlEncode("Unable to update Orders. Reason: " + ex.Message).Replace("'", "'").Replace("\r\n", "<br />"));
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
return;
}
//Code for updating the database can go here...
clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';",
labelID, "Order " + changedRow["OrderID"] + ", ProductID " + changedRow["ProductID"] + " updated");
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
}
}
}
--------------------------
----ASPX Code----------------------
--------
<%@ Page Language="c#" AutoEventWireup="false" Codebehind="DefaultCS.aspx
.cs" Inherits="Telerik.GridExam
plesCSharp
.AJAX.Edit
OnDblClick
.DefaultCS
" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.QuickSt
art" Assembly="Telerik.QuickSta
rt" %>
<%@ Register TagPrefix="telerik" TagName="Header" Src="~/Common/Header.ascx"
%>
<%@ Register TagPrefix="telerik" TagName="HeadTag" Src="~/Common/HeadTag.ascx
" %>
<%@ Register TagPrefix="telerik" TagName="Footer" Src="~/Common/Footer.ascx"
%>
<%@ Register TagPrefix="radG" Namespace="Telerik.WebCont
rols" Assembly="RadGrid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "
http://www.w3.org/tr/xhtml11/DTD/xhtml11.dtd"
>
<html>
<head>
<telerik:headtag runat="server" id="Headtag2"></telerik:head
tag>
<!-- custom head section -->
<script type="text/javascript">
<!--
var HasChanges, inputs, lastChanged, editedRow;
function RowClick(index)
{
if ((this.Rows[index].ItemTyp
e == "Item" || this.Rows[index].ItemType == "AlternatingItem"))
{
if(editedRow != null && HasChanges)
{
if(confirm("Update changes?"))
{
HasChanges = false;
window["<%=RadGrid1.ClientI
D%>"].AjaxR
equest("<%=
RadGrid1.U
niqueID%>",
"Update:" + editedRow.RealIndex);
}
else
{
HasChanges = false;
}
}
}
}
function RowDblClick(index)
{
if (this.Rows[index].ItemType
== "Item" || this.Rows[index].ItemType == "AlternatingItem")
{
if(editedRow && HasChanges)
{
if(confirm("Update changes?"))
{
HasChanges = false;
window["<%=RadGrid1.ClientI
D%>"].AjaxR
equest("<%=
RadGrid1.U
niqueID%>",
"Update:" + editedRow.RealIndex);
}
else
{
HasChanges = false;
}
}
window["<%=RadGrid1.ClientI
D%>"].AjaxR
equest("<%=
RadGrid1.U
niqueID%>",
"Edit:" + this.Rows[index].RealIndex
);
editedRow = this.Rows[index];
}
}
function RowCreated(row)
{
if(row.ItemType == "EditItem")
{
inputs = row.Control.getElementsByT
agName("in
put");
for (var i = 0; i < inputs.length;i++)
{
inputs[i].onchange = TrackChanges;
}
setTimeout(function(){inpu
ts[0].focu
s();},100)
;
}
}
function RequestStart(e)
{
var canRequest = true;
if (HasChanges)
{
canRequest = confirm("Cancel changes?");
}
if(canRequest)
{
HasChanges = false;
return true;
}
else
{
lastChanged.select();
return false;
}
}
function TrackChanges(e)
{
lastChanged = GetCurrentElement(e);
HasChanges = true;
}
function GetCurrentElement(e)
{
if(!e)
var e = window.event;
if (e.srcElement)
{
return e.srcElement;
}
if(e.target)
{
return e.target;
}
}
-->
</script>
<!-- end of custom head section -->
</head>
<body class="BODY">
<form runat="server" id="mainForm" method="post" style="WIDTH:100%">
<telerik:header runat="server" id="Header1" navigationlanguage="CS"></te
lerik:head
er>
<!-- content start -->
<radg:radgrid id="RadGrid1" Width="97%" skin="WinXP" EnableAJAX="true" ShowStatusBar="true" allowsorting="True"
pagesize="20" GridLines="None" allowpaging="True" runat="server">
<pagerstyle mode="NumericPages"/>
<mastertableview editmode="InPlace" Width="100%"/>
<clientsettings>
<clientevents onrequeststart="RequestSta
rt" OnRowClick="RowClick" onrowdblclick="RowDblClick
" onrowcreated="RowCreated"></
clienteven
ts>
</clientsettings>
</radg:radgrid>
<br />
<asp:label id="Label1" Runat="server"></asp:label>
<!-- content end -->
<telerik:footer runat="server" id="Footer1"></telerik:foote
r>
</form>
</body>
</html>
You may want to allow the user to force grid item in edit mode by simply double-clicking the respective item (an easy and intuitive approach). This demo illustrates how to switch a row in edit mode by double-clicking an arbitrary grid item and how to update this row when the user clicks another row in the grid. Furthermore, a user-friendly confirm dialog will be displayed to prompt whether the operation should be propagated or not.
The example uses RadGridClientObject.AjaxRe
quest() calls (wiring the RowClick and RowDblClick events) and the onchange event of the inputs in the grid rows used for editing (the handler for the onchange event is assigned in the RowCreated handler of the grid).
Additional editing tips and tricks (for example how to perform batch updates) you can find in the How-to subchapter from the Insert/Update/Delete records section in the product's online help:
How-to's
using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.QuickStart;
using Telerik.QuickStart.Grid;
using Telerik.WebControls;
namespace Telerik.GridExamplesCSharp
.AJAX.Edit
OnDblClick
{
public abstract class DefaultCS : XhtmlPage
{
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.RadGrid1.NeedDataSour
ce += new Telerik.WebControls.GridNe
edDataSour
ceEventHan
dler(this.
RadGrid1_N
eedDataSou
rce);
this.RadGrid1.ColumnCreate
d += new Telerik.WebControls.GridCo
lumnCreate
dEventHand
ler(this.R
adGrid1_Co
lumnCreate
d);
this.Load += new EventHandler(this.Page_Loa
d);
}
#endregion
protected System.Web.UI.WebControls.
Label Label1;
protected Telerik.WebControls.RadGri
d RadGrid1;
protected void Page_Load(object sender, System.EventArgs e)
{
string clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '';", this.Label1.ClientID);
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
}
private void RadGrid1_NeedDataSource(ob
ject source, Telerik.WebControls.GridNe
edDataSour
ceEventArg
s e)
{
RadGrid1.DataSource = OrderDetails;
}
private DataTable OrderDetails
{
get
{
if (this.Session["OrderDetail
s"] != null)
{
return (DataTable)this.Session["O
rderDetail
s"];
}
DataTable res = DataSourceHelperCS.GetData
Table("SEL
ECT * FROM [Order Details]");
this.Session["OrderDetails
"] = res;
return res;
}
}
protected override void RaisePostBackEvent(IPostBa
ckEventHan
dler sourceControl, string eventArgument)
{
base.RaisePostBackEvent(so
urceContro
l, eventArgument);
if (sourceControl is RadGrid)
{
string[] postBackEventArgumentData = eventArgument.Split(':');
switch (postBackEventArgumentData
[0])
{
case "Edit":
{
((RadGrid1.MasterTableView
.Controls[
0] as Table).Rows[int.Parse(post
BackEventA
rgumentDat
a[1])] as GridItem).Edit = true;
RadGrid1.Rebind();
break;
}
case "Update":
{
GridItem item = ((RadGrid1.MasterTableView
.Controls[
0] as Table).Rows[int.Parse(post
BackEventA
rgumentDat
a[1])] as GridItem);
UpdateItem(item);
item.Edit = false;
RadGrid1.Rebind();
break;
}
}
}
}
private void RadGrid1_ColumnCreated(obj
ect sender, Telerik.WebControls.GridCo
lumnCreate
dEventArgs
e)
{
if (e.Column is GridBoundColumn)
{
if ((e.Column as GridBoundColumn).DataField
== "OrderID" || (e.Column as GridBoundColumn).DataField
== "ProductID")
{
(e.Column as GridBoundColumn).ReadOnly = true;
e.Column.HeaderStyle.Width
= Unit.Pixel(60);
}
else
{
e.Column.HeaderStyle.Width
= Unit.Pixel(150);
}
}
}
private void UpdateItem(GridItem item)
{
GridEditableItem editedItem = item as GridEditableItem;
DataTable ordersTable = this.OrderDetails;
//Locate the changed row in the DataSource
DataRow[] changedRows = ordersTable.Select( "OrderID = " + editedItem["OrderID"].Text
+ " AND " + " ProductID = " + editedItem["ProductID"].Te
xt );
string labelID = this.Label1.ClientID;
string clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';", labelID, "");
if (changedRows.Length != 1)
{
clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';",
labelID, "Unbale to locate the Order for updating.");
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
//The GridTableView will fill the values from all editable columns in the hash
item.OwnerTableView.Extrac
tValuesFro
mItem(newV
alues, editedItem);
DataRow changedRow = changedRows[0];
changedRow.BeginEdit();
try
{
foreach( DictionaryEntry entry in newValues )
{
changedRow[(string)entry.K
ey] = entry.Value;
}
changedRow.EndEdit();
}
catch( Exception ex )
{
changedRow.CancelEdit();
//In AJAX mode this will update the corresponding label text, client-side:
clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';",
labelID, Server.HtmlEncode("Unable to update Orders. Reason: " + ex.Message).Replace("'", "'").Replace("\r\n", "<br />"));
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
return;
}
//Code for updating the database can go here...
clientExecute = string.Format("document.ge
tElementBy
Id('{0}').
innerHTML = '{1}';",
labelID, "Order " + changedRow["OrderID"] + ", ProductID " + changedRow["ProductID"] + " updated");
this.RadGrid1.ClientSettin
gs.ClientE
vents.OnGr
idCreated = clientExecute;
}
}
}
<%@ Page Language="c#" AutoEventWireup="false" Codebehind="DefaultCS.aspx
.cs" Inherits="Telerik.GridExam
plesCSharp
.AJAX.Edit
OnDblClick
.DefaultCS
" %>
<%@ Register TagPrefix="telerik" Namespace="Telerik.QuickSt
art" Assembly="Telerik.QuickSta
rt" %>
<%@ Register TagPrefix="telerik" TagName="Header" Src="~/Common/Header.ascx"
%>
<%@ Register TagPrefix="telerik" TagName="HeadTag" Src="~/Common/HeadTag.ascx
" %>
<%@ Register TagPrefix="telerik" TagName="Footer" Src="~/Common/Footer.ascx"
%>
<%@ Register TagPrefix="radG" Namespace="Telerik.WebCont
rols" Assembly="RadGrid" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "
http://www.w3.org/tr/xhtml11/DTD/xhtml11.dtd"
>
<html>
<head>
<telerik:headtag runat="server" id="Headtag2"></telerik:head
tag>
<!-- custom head section -->
<script type="text/javascript">
<!--
var HasChanges, inputs, lastChanged, editedRow;
function RowClick(index)
{
if ((this.Rows[index].ItemTyp
e == "Item" || this.Rows[index].ItemType == "AlternatingItem"))
{
if(editedRow != null && HasChanges)
{
if(confirm("Update changes?"))
{
HasChanges = false;
window["<%=RadGrid1.ClientI
D%>"].AjaxR
equest("<%=
RadGrid1.U
niqueID%>",
"Update:" + editedRow.RealIndex);
}
else
{
HasChanges = false;
}
}
}
}
function RowDblClick(index)
{
if (this.Rows[index].ItemType
== "Item" || this.Rows[index].ItemType == "AlternatingItem")
{
if(editedRow && HasChanges)
{
if(confirm("Update changes?"))
{
HasChanges = false;
window["<%=RadGrid1.ClientI
D%>"].AjaxR
equest("<%=
RadGrid1.U
niqueID%>",
"Update:" + editedRow.RealIndex);
}
else
{
HasChanges = false;
}
}
window["<%=RadGrid1.ClientI
D%>"].AjaxR
equest("<%=
RadGrid1.U
niqueID%>",
"Edit:" + this.Rows[index].RealIndex
);
editedRow = this.Rows[index];
}
}
function RowCreated(row)
{
if(row.ItemType == "EditItem")
{
inputs = row.Control.getElementsByT
agName("in
put");
for (var i = 0; i < inputs.length;i++)
{
inputs[i].onchange = TrackChanges;
}
setTimeout(function(){inpu
ts[0].focu
s();},100)
;
}
}
function RequestStart(e)
{
var canRequest = true;
if (HasChanges)
{
canRequest = confirm("Cancel changes?");
}
if(canRequest)
{
HasChanges = false;
return true;
}
else
{
lastChanged.select();
return false;
}
}
function TrackChanges(e)
{
lastChanged = GetCurrentElement(e);
HasChanges = true;
}
function GetCurrentElement(e)
{
if(!e)
var e = window.event;
if (e.srcElement)
{
return e.srcElement;
}
if(e.target)
{
return e.target;
}
}
-->
</script>
<!-- end of custom head section -->
</head>
<body class="BODY">
<form runat="server" id="mainForm" method="post" style="WIDTH:100%">
<telerik:header runat="server" id="Header1" navigationlanguage="CS"></te
lerik:head
er>
<!-- content start -->
<radg:radgrid id="RadGrid1" Width="97%" skin="WinXP" EnableAJAX="true" ShowStatusBar="true" allowsorting="True"
pagesize="20" GridLines="None" allowpaging="True" runat="server">
<pagerstyle mode="NumericPages"/>
<mastertableview editmode="InPlace" Width="100%"/>
<clientsettings>
<clientevents onrequeststart="RequestSta
rt" OnRowClick="RowClick" onrowdblclick="RowDblClick
" onrowcreated="RowCreated"></
clienteven
ts>
</clientsettings>
</radg:radgrid>
<br />
<asp:label id="Label1" Runat="server"></asp:label>
<!-- content end -->
<telerik:footer runat="server" id="Footer1"></telerik:foote
r>
</form>
</body>
</html>
Hope this help