This example demonstrates how to create data item templates and use the WebMethod attribute to update data in templated columns without refreshing the entire grid.
Overview
Follow the steps below:
- Specify a column's DataItemTemplate property and add a control to the template. In the control's
Init
event handler, specify the control'sClientInstanceName
property based on the row's key value.ASPx<dx:GridViewDataSpinEditColumn FieldName="C2" Caption="Numeric (Live)"> <DataItemTemplate> <dx:ASPxLabel ID="labelC1" runat="server" Text='<%# Eval("C2") %>' OnInit="labelC1_Init" /> </DataItemTemplate> </dx:GridViewDataSpinEditColumn> <dx:GridViewDataCheckColumn FieldName="C4" Caption="Boolean (Live)"> <DataItemTemplate> <dx:ASPxCheckBox ID="cbC4" runat="server" Value='<%# Convert.ToBoolean(Eval("C4")) %>' ReadOnly="true" OnInit="cbC4_Init" /> </DataItemTemplate> </dx:GridViewDataCheckColumn>
C#protected void labelC1_Init(object sender, EventArgs e) { ASPxLabel label = sender as ASPxLabel; GridViewDataItemTemplateContainer container = label.NamingContainer as GridViewDataItemTemplateContainer; label.ClientInstanceName = "labelC1_" + container.KeyValue; } protected void cbC4_Init(object sender, EventArgs e) { ASPxCheckBox cb = sender as ASPxCheckBox; GridViewDataItemTemplateContainer container = cb.NamingContainer as GridViewDataItemTemplateContainer; cb.ClientInstanceName = "cbC4_" + container.KeyValue; }
- Send a request to the server to get new values and use the WebMethod attribute to pass the values to the client.JavaScript
PageMethods.GetUpdatedDataFromServer(keys, onSucess, onError);
C#[WebMethod] public static string GetUpdatedDataFromServer(int[] keys) { ChangeAllColumnDataRandomly(); List<GridDataItem> GridData = GetDataSource(); List<GridDataItem> newDataRequiredForClient = new List<GridDataItem>(); foreach (int keyValue in keys) { GridDataItem item = GridData.Find(x => x.ID == keyValue); newDataRequiredForClient.Add(item); } var jsonSerialiser = new JavaScriptSerializer(); var json = jsonSerialiser.Serialize(newDataRequiredForClient); return json; } public static void ChangeAllColumnDataRandomly() { // ... } public static List<GridDataItem> GetDataSource() { // ... }
- Update data in templated columns on the client side or specify an error message.JavaScript
function onSucess(result) { var items = JSON.parse(result); for (var i = 0; i < items.length; i++) { var label = ASPxClientControl.GetControlCollection().GetByName("labelC1_" + items[i].ID); label.SetText(items[i].C2); var checkBox = ASPxClientControl.GetControlCollection().GetByName("cbC4_" + items[i].ID); checkBox.SetChecked(items[i].C4); } } function onError(result) { alert('Something wrong!'); }
Files to Review
- Default.aspx (VB: Default.aspx)
- Default.aspx.cs (VB: Default.aspx.vb)
Documentation
More Examples
Example Code
ASPx<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register Assembly="DevExpress.Web.v17.1, Version=17.1.17.0, Culture=neutral, PublicKeyToken=b88d1754d700e49a"
Namespace="DevExpress.Web" TagPrefix="dx" %>
<!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></title>
<script type="text/javascript">
function RequestNewData() {
var startIndex = gridView.GetTopVisibleIndex();
var rowsCount = gridView.GetVisibleRowsOnPage();
var keys = new Array(rowsCount);
for (var i = startIndex; i < startIndex + rowsCount; i++) {
keys[i - startIndex] = gridView.GetRowKey(i);
}
PageMethods.GetUpdatedDataFromServer(keys, onSucess, onError);
}
function onSucess(result) {
var items = JSON.parse(result);
for (var i = 0; i < items.length; i++) {
var label = ASPxClientControl.GetControlCollection().GetByName("labelC1_" + items[i].ID);
label.SetText(items[i].C2);
var checkBox = ASPxClientControl.GetControlCollection().GetByName("cbC4_" + items[i].ID);
checkBox.SetChecked(items[i].C4);
}
}
function onError(result) {
alert('Something wrong!');
}
</script>
</head>
<body>
<form id="frmMain" runat="server">
<asp:ScriptManager runat="server" ID="scriptManager" EnablePageMethods="true">
</asp:ScriptManager>
<table>
<tr>
<td>
<dx:ASPxButton ID="btUpdateData" runat="server" Text="Refresh Data" AutoPostBack="false" ClientInstanceName="btUpdateData">
<ClientSideEvents Click="function(s, e){
RequestNewData();
}" />
</dx:ASPxButton>
</td>
<td>
<dx:ASPxCheckBox ID="cbRefreshAutomatically" runat="server" Text="Refresh Automatically">
<ClientSideEvents CheckedChanged="function(s, e){
timer.SetEnabled(s.GetChecked());
btUpdateData.SetEnabled(!s.GetChecked());
}" />
</dx:ASPxCheckBox>
</td>
</tr>
</table>
<dx:ASPxGridView ID="gridView" runat="server" KeyFieldName="ID" ClientInstanceName="gridView"
OnRowInserting="Grid_RowInserting" OnRowUpdating="Grid_RowUpdating" OnRowDeleting="Grid_RowDeleting">
<Columns>
<dx:GridViewCommandColumn ShowNewButtonInHeader="true" ShowDeleteButton="true" />
<dx:GridViewDataColumn FieldName="ID">
</dx:GridViewDataColumn>
<dx:GridViewDataDateColumn FieldName="C5" Caption="Date" />
<dx:GridViewDataSpinEditColumn FieldName="C2" Caption="Numeric (Live)">
<DataItemTemplate>
<dx:ASPxLabel ID="labelC1" runat="server" Text='<%# Eval("C2") %>' OnInit="labelC1_Init"></dx:ASPxLabel>
</DataItemTemplate>
</dx:GridViewDataSpinEditColumn>
<dx:GridViewDataCheckColumn FieldName="C4" Caption="Boolean (Live)">
<DataItemTemplate>
<dx:ASPxCheckBox ID="cbC4" runat="server" Value='<%# Convert.ToBoolean(Eval("C4")) %>'
ReadOnly="true" OnInit="cbC4_Init">
</dx:ASPxCheckBox>
</DataItemTemplate>
</dx:GridViewDataCheckColumn>
</Columns>
</dx:ASPxGridView>
<dx:ASPxTimer ID="timer" runat="server" Enabled="false" Interval="2000" ClientInstanceName="timer">
<ClientSideEvents Tick="function(s, e){ RequestNewData(); }" />
</dx:ASPxTimer>
</form>
</body>
</html>
C#using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.Linq;
using DevExpress.Web.Data;
using DevExpress.Web;
using System.Web.Services;
using System.Web;
using System.Web.Script.Serialization;
public partial class _Default: System.Web.UI.Page {
protected void labelC1_Init(object sender, EventArgs e) {
ASPxLabel label = sender as ASPxLabel;
GridViewDataItemTemplateContainer container = label.NamingContainer as GridViewDataItemTemplateContainer;
label.ClientInstanceName = "labelC1_" + container.KeyValue;
}
protected void cbC4_Init(object sender, EventArgs e) {
ASPxCheckBox cb = sender as ASPxCheckBox;
GridViewDataItemTemplateContainer container = cb.NamingContainer as GridViewDataItemTemplateContainer;
cb.ClientInstanceName = "cbC4_" + container.KeyValue;
}
[WebMethod]
public static string GetUpdatedDataFromServer(int[] keys) {
ChangeAllColumnDataRandomly();
List<GridDataItem> GridData = GetDataSource();
List<GridDataItem> newDataRequiredForClient = new List<GridDataItem>();
foreach (int keyValue in keys) {
GridDataItem item = GridData.Find(x => x.ID == keyValue);
newDataRequiredForClient.Add(item);
}
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(newDataRequiredForClient);
return json;
}
public static void ChangeAllColumnDataRandomly() {
List<GridDataItem> GridData = GetDataSource();
Random random = new Random();
int randomNumber;
for (int i = 0; i < GridData.Count; i++) {
randomNumber = random.Next(0, 200);
GridData[i].C2 = randomNumber;
GridData[i].C4 = randomNumber % 4 != 0;
}
}
public static List<GridDataItem> GetDataSource() {
var key = "34FAA431-CF79-4869-9488-93F6AAE81263";
List<GridDataItem> GridData = (List<GridDataItem>)HttpContext.Current.Session[key];
return GridData;
}
#region Standard data
protected List<GridDataItem> GridData
{
get
{
var key = "34FAA431-CF79-4869-9488-93F6AAE81263";
if (!IsPostBack || Session[key] == null)
Session[key] = Enumerable.Range(0, 100).Select(i => new GridDataItem
{
ID = i,
C1 = i % 2,
C2 = i * (i % 3),
C3 = "C3 " + i,
C4 = i % 4 != 0,
C5 = new DateTime(2013 + i, 12, 16)
}).ToList();
return (List<GridDataItem>)Session[key];
}
}
protected void Page_Load(object sender, EventArgs e) {
gridView.DataSource = GridData;
gridView.DataBind();
}
protected void Grid_RowInserting(object sender, ASPxDataInsertingEventArgs e) {
InsertNewItem(e.NewValues);
CancelEditing(e);
}
protected void Grid_RowUpdating(object sender, ASPxDataUpdatingEventArgs e) {
UpdateItem(e.Keys, e.NewValues);
CancelEditing(e);
}
protected void Grid_RowDeleting(object sender, ASPxDataDeletingEventArgs e) {
DeleteItem(e.Keys, e.Values);
CancelEditing(e);
}
protected GridDataItem InsertNewItem(OrderedDictionary newValues) {
var item = new GridDataItem() { ID = GridData.Count };
LoadNewValues(item, newValues);
GridData.Add(item);
return item;
}
protected GridDataItem UpdateItem(OrderedDictionary keys, OrderedDictionary newValues) {
var id = Convert.ToInt32(keys["ID"]);
var item = GridData.First(i => i.ID == id);
LoadNewValues(item, newValues);
return item;
}
protected GridDataItem DeleteItem(OrderedDictionary keys, OrderedDictionary values) {
var id = Convert.ToInt32(keys["ID"]);
var item = GridData.First(i => i.ID == id);
GridData.Remove(item);
return item;
}
protected void LoadNewValues(GridDataItem item, OrderedDictionary values) {
item.C1 = Convert.ToInt32(values["C1"]);
item.C2 = Convert.ToDouble(values["C2"]);
item.C3 = Convert.ToString(values["C3"]);
item.C4 = Convert.ToBoolean(values["C4"]);
item.C5 = Convert.ToDateTime(values["C5"]);
}
protected void CancelEditing(CancelEventArgs e) {
e.Cancel = true;
gridView.CancelEdit();
}
public class GridDataItem {
public int ID { get; set; }
public int C1 { get; set; }
public double C2 { get; set; }
public string C3 { get; set; }
public bool C4 { get; set; }
public DateTime C5 { get; set; }
}
#endregion
}