可能你想讓用戶雙擊item就進入edit模式。
這章就是告訴大家 如何使得雙擊row進入row的編輯模式,儅用戶點擊其他行的時候更新row,而且彈出一個confirm框。
下面的例子使用了RadGrid.AjaxRequest() , OnRowClick , onrowdblclick 和grid裏面inputs的onchange事件
[ASPX]
<script type="text/javascript">
<!--
var HasChanges, inputs, lastChanged, editedRow;
function RowClick(index)
{
if ((this.Rows[index].ItemType == "Item" || this.Rows[index].ItemType == "AlternatingItem"))
{
if(editedRow != null && HasChanges)
{
if(confirm("Update changes?"))
{
HasChanges = false;
window["<%= RadGrid1.ClientID %>"].AjaxRequest("<%= RadGrid1.UniqueID %>", "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.ClientID %>"].AjaxRequest("<%= RadGrid1.UniqueID %>", "Update:" + editedRow.RealIndex);
}
else
{
HasChanges = false;
}
}
window["<%= RadGrid1.ClientID %>"].AjaxRequest("<%= RadGrid1.UniqueID %>", "Edit:" + this.Rows[index].RealIndex);
editedRow = this.Rows[index];
}
}
function RowCreated(row)
{
if(row.ItemType == "EditItem")
{
inputs = row.Control.getElementsByTagName("input");
for (var i = 0; i < inputs.length;i++)
{
inputs[i].onchange = TrackChanges;
}
inputs[0].focus();
}
}
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>
<radg:radgrid id="RadGrid1" Width="95%" cssclass="RadGrid" EnableAjax="true" allowsorting="True"
pagesize="20" GridLines="None" allowpaging="True" runat="server">
<headerstyle cssclass="GridHeader"/>
<pagerstyle mode="NumericPages" cssclass="GridPager" Height="18px"/>
<itemstyle cssclass="GridRow" Height="20px"/>
<alternatingitemstyle cssclass="GridRow" Height="20px"/>
<mastertableview editmode="InPlace" cssclass="MasterTable" Width="100%"/>
<clientsettings>
<clientevents onrequeststart="RequestStart" OnRowClick="RowClick" onrowdblclick="RowDblClick"
onrowcreated= "RowCreated"></clientevents>
</clientsettings>
</radg:radgrid>
<asp:label id="Label1" Runat="server"></asp:label>
<!--
var HasChanges, inputs, lastChanged, editedRow;
function RowClick(index)
{
if ((this.Rows[index].ItemType == "Item" || this.Rows[index].ItemType == "AlternatingItem"))
{
if(editedRow != null && HasChanges)
{
if(confirm("Update changes?"))
{
HasChanges = false;
window["<%= RadGrid1.ClientID %>"].AjaxRequest("<%= RadGrid1.UniqueID %>", "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.ClientID %>"].AjaxRequest("<%= RadGrid1.UniqueID %>", "Update:" + editedRow.RealIndex);
}
else
{
HasChanges = false;
}
}
window["<%= RadGrid1.ClientID %>"].AjaxRequest("<%= RadGrid1.UniqueID %>", "Edit:" + this.Rows[index].RealIndex);
editedRow = this.Rows[index];
}
}
function RowCreated(row)
{
if(row.ItemType == "EditItem")
{
inputs = row.Control.getElementsByTagName("input");
for (var i = 0; i < inputs.length;i++)
{
inputs[i].onchange = TrackChanges;
}
inputs[0].focus();
}
}
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>
<radg:radgrid id="RadGrid1" Width="95%" cssclass="RadGrid" EnableAjax="true" allowsorting="True"
pagesize="20" GridLines="None" allowpaging="True" runat="server">
<headerstyle cssclass="GridHeader"/>
<pagerstyle mode="NumericPages" cssclass="GridPager" Height="18px"/>
<itemstyle cssclass="GridRow" Height="20px"/>
<alternatingitemstyle cssclass="GridRow" Height="20px"/>
<mastertableview editmode="InPlace" cssclass="MasterTable" Width="100%"/>
<clientsettings>
<clientevents onrequeststart="RequestStart" OnRowClick="RowClick" onrowdblclick="RowDblClick"
onrowcreated= "RowCreated"></clientevents>
</clientsettings>
</radg:radgrid>
<asp:label id="Label1" Runat="server"></asp:label>
And in the code-behind:
[C#]
private void InitializeComponent()
{
this.RadGrid1.NeedDataSource += new Telerik.WebControls.GridNeedDataSourceEventHandler(this.RadGrid1_NeedDataSource);
this.RadGrid1.ColumnCreated += new Telerik.WebControls.GridColumnCreatedEventHandler(this.RadGrid1_ColumnCreated);
this.Load += new EventHandler(this.Page_Load);
}
protected System.Web.UI.WebControls.Label Label1;
protected Telerik.WebControls.RadGrid RadGrid1;
protected void Page_Load(object sender, System.EventArgs e)
{
string clientExecute = string.Format("document.getElementById('{0}').innerHTML = '';", this.Label1.ClientID);
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
}
private void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = OrderDetails;
}
private DataTable OrderDetails
{
get
{
if (this.Session["OrderDetails"] != null)
{
return (DataTable)this.Session["OrderDetails"];
}
DataTable res = DataSourceHelperCS.GetDataTable("SELECT * FROM [Order Details]");
this.Session["OrderDetails"] = res;
return res;
}
}
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
base.RaisePostBackEvent(sourceControl, eventArgument);
if (sourceControl is RadGrid)
{
string[] postBackEventArgumentData = eventArgument.Split(':');
switch (postBackEventArgumentData[0])
{
case "Edit":
{
((RadGrid1.MasterTableView.Controls[0] as Table).Rows[int.Parse(postBackEventArgumentData[1])] as GridItem).Edit = true;
RadGrid1.Rebind();
break;
}
case "Update":
{
GridItem item = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[int.Parse(postBackEventArgumentData[1])] as GridItem);
UpdateItem(item);
RadGrid1.Rebind();
break;
}
}
}
}
private void RadGrid1_ColumnCreated(object sender, Telerik.WebControls.GridColumnCreatedEventArgs 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"].Text );
string labelID = this.Label1.ClientID;
string clientExecute = string.Format("document.getElementById('{0}').innerHTML = '{1}';", labelID, "");
if (changedRows.Length != 1)
{
clientExecute = string.Format("document.getElementById('{0}').innerHTML = '{1}';",
labelID, "Unbale to locate the Order for updating.");
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
//The GridTableView will fill the values from all editable columns in the hash
item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
DataRow changedRow = changedRows[0];
changedRow.BeginEdit();
try
{
foreach( DictionaryEntry entry in newValues )
{
changedRow[(string)entry.Key] = 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.getElementById('{0}').innerHTML = '{1}';",
labelID, Server.HtmlEncode("Unable to update Orders. Reason: " + ex.Message).Replace("'", "'").Replace("\r\n", "<br />"));
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
return;
}
//Code for updating the database can go here
clientExecute = string.Format("document.getElementById('{0}').innerHTML = '{1}';",
labelID, "Order " + changedRow["OrderID"] + ", ProductID " + changedRow["ProductID"] + " updated");
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
}
{
this.RadGrid1.NeedDataSource += new Telerik.WebControls.GridNeedDataSourceEventHandler(this.RadGrid1_NeedDataSource);
this.RadGrid1.ColumnCreated += new Telerik.WebControls.GridColumnCreatedEventHandler(this.RadGrid1_ColumnCreated);
this.Load += new EventHandler(this.Page_Load);
}
protected System.Web.UI.WebControls.Label Label1;
protected Telerik.WebControls.RadGrid RadGrid1;
protected void Page_Load(object sender, System.EventArgs e)
{
string clientExecute = string.Format("document.getElementById('{0}').innerHTML = '';", this.Label1.ClientID);
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
}
private void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = OrderDetails;
}
private DataTable OrderDetails
{
get
{
if (this.Session["OrderDetails"] != null)
{
return (DataTable)this.Session["OrderDetails"];
}
DataTable res = DataSourceHelperCS.GetDataTable("SELECT * FROM [Order Details]");
this.Session["OrderDetails"] = res;
return res;
}
}
protected override void RaisePostBackEvent(IPostBackEventHandler sourceControl, string eventArgument)
{
base.RaisePostBackEvent(sourceControl, eventArgument);
if (sourceControl is RadGrid)
{
string[] postBackEventArgumentData = eventArgument.Split(':');
switch (postBackEventArgumentData[0])
{
case "Edit":
{
((RadGrid1.MasterTableView.Controls[0] as Table).Rows[int.Parse(postBackEventArgumentData[1])] as GridItem).Edit = true;
RadGrid1.Rebind();
break;
}
case "Update":
{
GridItem item = ((RadGrid1.MasterTableView.Controls[0] as Table).Rows[int.Parse(postBackEventArgumentData[1])] as GridItem);
UpdateItem(item);
RadGrid1.Rebind();
break;
}
}
}
}
private void RadGrid1_ColumnCreated(object sender, Telerik.WebControls.GridColumnCreatedEventArgs 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"].Text );
string labelID = this.Label1.ClientID;
string clientExecute = string.Format("document.getElementById('{0}').innerHTML = '{1}';", labelID, "");
if (changedRows.Length != 1)
{
clientExecute = string.Format("document.getElementById('{0}').innerHTML = '{1}';",
labelID, "Unbale to locate the Order for updating.");
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
return;
}
//Update new values
Hashtable newValues = new Hashtable();
//The GridTableView will fill the values from all editable columns in the hash
item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);
DataRow changedRow = changedRows[0];
changedRow.BeginEdit();
try
{
foreach( DictionaryEntry entry in newValues )
{
changedRow[(string)entry.Key] = 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.getElementById('{0}').innerHTML = '{1}';",
labelID, Server.HtmlEncode("Unable to update Orders. Reason: " + ex.Message).Replace("'", "'").Replace("\r\n", "<br />"));
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
return;
}
//Code for updating the database can go here
clientExecute = string.Format("document.getElementById('{0}').innerHTML = '{1}';",
labelID, "Order " + changedRow["OrderID"] + ", ProductID " + changedRow["ProductID"] + " updated");
this.RadGrid1.ClientSettings.ClientEvents.OnGridCreated = clientExecute;
}