RadGrid for ASP.NET

Updating values in-place and with edit forms Send comments on this topic.
Insert/Update/Delete records > Update records > Updating values in-place and with edit forms

Glossary Item Box

Generally, there are three common techniques to update grid row with InPlace and EditForms edit mode:

  1. Enabling the automatic operations for the control - this is a codeless approach and requires zero lines of code (see this online demo for more info).
  2. Use the ExtractValuesFromItem(dictonaryObject, editedItem) method (available since version 3.0 of Telerik RadGrid). You can create an empty dictionary object and pass it as first parameter of the ExtractValuesFromItem() method to extract the values from the edited item (which is the second parameter to that method). The dictionary object will hold key -> value pairs where each key will be the DataField of the edited field column and the corresponding value will be the new data entered by the user. 
  3. Fetch the data from each edited field individually through the auto-generated column editors. For this purpose you will need to iterate through the editable fields for the edited grid row and modify the grid source on every loop.

    The code below demonstrates how to refresh the grid content with the new data on UpdateCommand using:
  4. The ExtractValuesFromItem method
    Note that we use ViewState property (named GridSource) to update the grid source:
    ASPX/ASCX Copy Code
    <rad:RadGrid id="RadGrid1" runat="server">
       
    <MasterTableView AutoGenerateColumns="False">
        
    <Columns>
         
    <rad:GridBoundColumn HeaderText="OrderID" DataField="OrderID" ReadOnly="True" UniqueName="OrderID"
           
    Display= "False"></rad:GridBoundColumn>
         
    <rad:GridBoundColumn HeaderText="EmployeeID" DataField="EmployeeID" UniqueName="EmployeeID"></rad:GridBoundColumn>
         
    <rad:GridBoundColumn HeaderText="OrderDate" DataField="OrderDate" UniqueName="OrderDate"></rad:GridBoundColumn>
         
    <rad:GridBoundColumn HeaderText="ShipName" DataField="ShipName" UniqueName="ShipName"></rad:GridBoundColumn>
         
    <rad:GridEditCommandColumn UniqueName="EditCommandColumn"></rad:GridEditCommandColumn>
        
    </Columns>
       
    </MasterTableView>
    </
    rad:RadGrid>
    <
    asp:Label id="Label1" runat="server"></asp:Label>

    In the code-behind:

    C# Copy Code
    private DataTable GridSource
    {
      get
      {
       Object obj =
    this.ViewState["_gds"];
       
    if(obj != null)
       {
         
    return (DataTable)obj;
       }
       
    else
       {
        
    DataTable table = DataSourceHelperCS.GetDataTable( "SELECT TOP 10 OrderID, EmployeeID, OrderDate, ShipName FROM Orders");
        
    this.ViewState[ "_gds"] = table;
         
    return table;
       }
      }
    }
    private void RadGrid1_NeedDataSource(object source, Telerik.WebControls.GridNeedDataSourceEventArgs e)
    {
         RadGrid1.DataSource =
    this.GridSource;
    }


    private void RadGrid1_UpdateCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
    {
      GridEditableItem editedItem = e.Item
    as GridEditableItem;
      DataTable ordersTable =
    this.GridSource;

      
    //Locate the changed row in the DataSource
      
    DataRow[] changedRows = ordersTable.Select( "OrderID = " + editedItem["OrderID"].Text );

      
    if (changedRows.Length != 1)
      {
       
    this.Label1.Text += "Unable to locate the Order for updating.";
       e.Canceled = true;
       
    return;
      }

      
    //Update new values
      
    Hashtable newValues = new Hashtable();
      
    //The GridTableView will fill the values from all editable columns in the hash
      
    e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem);

      changedRows[0].BeginEdit();
      
    try
      {
       
    foreach( DictionaryEntry entry in newValues )
       {
        changedRows[0][(
    string)entry.Key] = entry.Value;
       }
       changedRows[0].EndEdit();
      }
      
    catch( Exception ex )
      {
       changedRows[0].CancelEdit();
       Label1.Text +=
    "Unable to update Orders. Reason: " + ex.Message;
       e.Canceled = true;
      }
    }
    VB.NET Copy Code
    Private ReadOnly Property GridSource As DataTable
     Get
      Dim obj As Object = Me.ViewState( "_gds")
      If (Not obj Is Nothing) Then
       Return CType(obj,DataTable)
      Else
       Dim table As DataTable = DataSourceHelperVB.GetDataTable( "SELECT TOP 10 OrderID, EmployeeID, OrderDate, ShipName FROM Orders")
       Me.ViewState( "_gds") = table
       Return table
      End If
     End Get
    End Property

    Private Sub RadGrid1_NeedDataSource(ByVal source As Object, ByVal e As Telerik.WebControls.GridNeedDataSourceEventArgs) Handles RadGrid1.NeedDataSource
     RadGrid1.DataSource = Me.GridSource
    End Sub


    Private Sub RadGrid1_UpdateCommand(ByVal source As Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.UpdateCommand
     Dim editedItem As GridEditableItem = CType(e.Item,GridEditableItem)
     Dim ordersTable As DataTable = Me.GridSource
     'Locate the changed row in the DataSource
     Dim changedRows() As DataRow = ordersTable.Select("OrderID = " & editedItem("OrderID").Text)
     If (changedRows.Length <> 1) Then
      Me.Label1.Text = Me.Label1.Text + "Unable to locate the Order for updating."
      e.Canceled = true
      Return
     End If
     'Update new values
     Dim newValues As Hashtable = New Hashtable
     'The GridTableView will fill the values from all editable columns in the hash
     e.Item.OwnerTableView.ExtractValuesFromItem(newValues, editedItem)
     changedRows(0).BeginEdit
     Try
      For Each entry As DictionaryEntry In newValues
       changedRows(0)(CType(entry.Key, String)) = entry.Value
      Next
      changedRows(0).EndEdit
     Catch ex As Exception
      changedRows(0).CancelEdit
      Label1.Text = Label1.Text & "Unable to update Orders. Reason: " & ex.Message
      e.Canceled = true
     End Try
    End Sub
  5. The auto-generated column editors:
    C# Copy Code
    private void RadGrid1_UpdateCommand(object source, Telerik.WebControls.GridCommandEventArgs e)
    {
    Label1.Text +=
    " Table to be updated: " + e.Item.OwnerTableView.DataMember + "<br>";

    GridEditableItem editedItem = e.Item
    as GridEditableItem;
    GridEditManager editMan = editedItem.EditManager;

    foreach( GridColumn column in e.Item.OwnerTableView.RenderColumns )
    {
     
    if ( column is IGridEditableColumn )
     {
      IGridEditableColumn editableCol = (column
    as IGridEditableColumn);
      
    if ( editableCol.IsEditable )
      {
       IGridColumnEditor editor = editMan.GetColumnEditor( editableCol );

       
    string editorText = "unknown";
       
    object editorValue = null;

       
    if ( editor is GridTextColumnEditor )
       {
        editorText = (editor
    as GridTextColumnEditor).Text;
        editorValue = (editor
    as GridTextColumnEditor).Text;
       }

       
    if ( editor is GridBoolColumnEditor )
       {
        editorText = (editor
    as GridBoolColumnEditor).Value.ToString();
        editorValue = (editor
    as GridBoolColumnEditor).Value;
       }

       
    if ( editor is GridDropDownColumnEditor )
       {
        editorText = (editor
    as GridDropDownColumnEditor).SelectedText + "; " +
         (editor
    as GridDropDownColumnEditor).SelectedValue;
        editorValue = (editor
    as GridDropDownColumnEditor).SelectedValue;
       }

       
    try
       {
        
    DataRow[] changedRows = this.GridSource.Select( "OrderID = " + editedItem["OrderID"].Text );
        changedRows[0][column.UniqueName] = editorValue;
        
    this.GridSource.AcceptChanges();
       }
       
    catch(Exception ex)
       {
        Label1.Text =
    "<strong>Unable to set value of column '" + column.UniqueName + "'</strong> - " + ex.Message;
        e.Canceled = true;
        
    break;
       }
      }
     }
    }
    }
    VB.NET Copy Code
    Private Sub RadGrid1_UpdateCommand(ByVal source As System.Object, ByVal e As Telerik.WebControls.GridCommandEventArgs) Handles RadGrid1.UpdateCommand

     Label1.Text += " Table to be updated: " + e.Item.OwnerTableView.DataMember + "<br>"

     Dim editedItem As GridEditableItem = CType(e.Item, GridEditableItem)
     Dim editMan As GridEditManager = editedItem.EditManager

     Dim column As GridColumn

     For Each column In e.Item.OwnerTableView.Columns
      If TypeOf column Is IGridEditableColumn Then
       Dim editableCol As IGridEditableColumn = CType(column, IGridEditableColumn)
       If (editableCol.IsEditable) Then
        Dim editor As IGridColumnEditor = editMan.GetColumnEditor(editableCol)

        Dim editorText As String = "unknown"
        Dim editorValue As Object = Nothing

        If (TypeOf editor Is GridTextColumnEditor) Then
         editorText = CType(editor, GridTextColumnEditor).Text
         editorValue = CType(editor, GridTextColumnEditor).Text
        End If

        If (TypeOf editor Is GridBoolColumnEditor) Then
         editorText = CType(editor, GridBoolColumnEditor).Value.ToString()
         editorValue = CType(editor, GridBoolColumnEditor).Value
        End If

        If (TypeOf editor Is GridDropDownColumnEditor) Then
         editorText = CType(editor, GridDropDownColumnEditor).SelectedText + "; "
         + CType(editor, GridDropDownColumnEditor).SelectedValue
         editorValue = CType(editor, GridDropDownColumnEditor).SelectedValue
        End If

        Try
          Dim changedRows As DataRow() = Me.GridSource. Select("OrderID = " + editedItem("OrderID").Text)
         changedRows(0)(column.UniqueName) = editorValue
          Me.GridSource.AcceptChanges()
        Catch ex As Exception
         Label1.Text = "<strong>Unable to set value of column '" + column.UniqueName + "'</strong> - " + ex.Message
         e.Canceled = True
        End Try

       End If
      End If
     Next


    End Sub

  6. Note: You can also see the Accessing cells and rows section for more details about update dependance from the Display/Visible/ReadOnly properties of grid columns.  
     

    Differences when using the EditItems collection with InPlace and EditForms edit mode

    The EditItems collection contains InPlace edit mode items. When you switch the edit type to EditForms, the EditItems collection holds the currently edited items but not their EditFormItems (which in this case hold the new values).
    If you would like your application to support both edit regimes, you have to make the following modification in the ItemCommand handler (this is an extraction from the CommandItem example of Telerik RadGrid):

    C# Copy Code
    if (e.CommandName == "UpdateEdited")
    {
       
    if (RadGrid1.EditIndexes.Count == 0)
       {
        
    return;
       }

       
    foreach (GridDataItem item in RadGrid1.EditItems)
       {
        GridEditableItem itemToEdit =
        (item.OwnerTableView.EditMode == GridEditMode.InPlace)?
        (GridEditableItem)item : (GridEditableItem)item.EditFormItem;
        UpdateItem(itemToEdit);
       }

       e.Item.OwnerTableView.Rebind();
       
    return;
    }
    VB.NET Copy Code
    If e.CommandName = "UpdateEdited" Then
       If RadGrid1.EditIndexes.Count = 0 Then
          Return
       End If

       Dim item As GridDataItem
       For Each item In RadGrid1.EditItems
          Dim itemToEdit As GridEditableItem = (IIf item.OwnerTableView.EditMode = GridEditMode.InPlace Then CType(item, GridEditableItem) Else CType(item.EditFormItem, GridEditableItem))
          UpdateItem(itemToEdit)
       Next item

       e.Item.OwnerTableView.Rebind()
       Return
    End If