This is a migrated thread and some comments may be shown as answers.

RadGrid_UpdateCommand

7 Answers 550 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Kaushal
Top achievements
Rank 1
Kaushal asked on 12 Nov 2010, 10:33 AM
Hi ALL,

          I have used rad grid with inline editing functionality, i have define RadGrid_UpdateCommand event for updating record, when i click on update button event get fired, but in event i used following code

var  EditedItem: GridEditableItem;
       KeyValue: Int64;
       NewValues: Hashtable;

EditedItem := e.Item as GridEditableItem;
 
  KeyValue := Int64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]['ID']);

  NewValues := new Hashtable;

 e.Item.OwnerTableView.ExtractValuesFromItem(NewValues, EditedItem);

But problem is here for NewValues hashtable i got null values, i didn't understand that what is the problem behind this.

I got the following error.

specified argument was out of the range of valid values. parameter name index

is there any problem to binding grid or something else.

Please help me.

Thanks
Kaushal
    

7 Answers, 1 is accepted

Sort by
0
Marin
Telerik team
answered on 15 Nov 2010, 01:23 PM
Hi Kaushal,

This error normally indicates that you are trying to access an element with index greater than the size of the collection. You can make sure that e.Item.ItemIndex is within range and that the 'ID' field is specified as a datakey for the MasterTableView. Also for futher information you may check the following help article:
Retrieving original values for edited item
Simple vs. Advance Data-binding

Let me know how this works for you and if you have any other questions.

Sincerely yours,
Marin
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
Kaushal
Top achievements
Rank 1
answered on 25 Nov 2010, 11:04 AM
Hi
      I have set the value of Datakey of MasterTableView also, but still getting problem,

Here i am mentioning my code please check it once and let me know if i am missing anything.

.aspx

<form id="form1" runat="server">
    <div>
     <telerik:RadScriptManager ID="ScriptManager1" runat="server" EnableTheming="True">
    </telerik:RadScriptManager>
        <telerik:radgrid id="RadGrid1" runat="server" onneeddatasource="RadGrid1_NeedDataSource"
            enableajax="true" autogenerateeditcolumn="True" showgrouppanel="True" width="99%"
            allowpaging="True" allowautomaticupdates="true" allowsorting="True" allowmultirowselection="True"
            height="100%" skin="Vista" onitemupdated="RadGrid1_ItemUpdated" onupdatecommand="RadGrid1_UpdateCommand">
                                    <ClientSettings AllowDragToGroup="True" AllowColumnsReorder="True" ReorderColumnsOnClient="True"
                                        AllowKeyboardNavigation="True">
                                        <Selecting AllowRowSelect="True" />
                                        <ClientEvents OnGridCreated="ResizeEvent" />
                                        <Scrolling AllowScroll="True" UseStaticHeaders="True" FrozenColumnsCount="3" />
                                        <Resizing ResizeGridOnColumnResize="True" AllowColumnResize="True" />
                                    </ClientSettings>
                                    <MasterTableView TableLayout="Fixed" Width="99%" GridLines="Both" AllowAutomaticUpdates="True"
                                        AutoGenerateColumns="False">
                                        <ExpandCollapseColumn>
                                            <HeaderStyle Width="20px" />
                                        </ExpandCollapseColumn>
                                        <EditFormSettings ColumnNumber="3">
                                            <EditColumn ButtonType="PushButton" UniqueName="EditCommandColumn1">
                                            </EditColumn>
                                        </EditFormSettings>
                                        <PagerStyle AlwaysVisible="True" />
                                        <HeaderStyle Wrap="False" />
                                    </MasterTableView>
                                </telerik:radgrid>
    </div>
    </form>

.cs file

GridTest = public partial class(TBasePage)
  private
  FGridHelper: TGridHelper;
  method GetDataGrid: RadGrid;
  protected
    method Page_Load(sender: Object; e: EventArgs);
    method RadGrid1_NeedDataSource(source: System.Object; e: Telerik.Web.UI.GridNeedDataSourceEventArgs);
    method RadGrid1_UpdateCommand(sender: Object; e: Telerik.Web.UI.GridCommandEventArgs);
    method RadGrid1_ItemUpdated(source: System.Object; e: Telerik.Web.UI.GridUpdatedEventArgs);
    property grdData: RadGrid read GetDataGrid;
  end;
 
implementation
 
method GridTest.GetDataGrid: RadGrid;
begin
  Result := RadGrid1;
end;
 
method GridTest.Page_Load(sender: Object; e: EventArgs);
begin
    FGridHelper := new TGridHelper(EasyIPConnection, grdData, Session);
end;
 
method GridTest.RadGrid1_ItemUpdated(source: System.Object; e: Telerik.Web.UI.GridUpdatedEventArgs);
begin
  FGridHelper.UpdateCommand(source, e);
end;
 
method GridTest.RadGrid1_UpdateCommand(sender: Object; e: Telerik.Web.UI.GridCommandEventArgs);
var
 editedItem : GridEditableItem;
  
 PlantID,PlantName,updateQuery  : String;
 NewValues: Hashtable;
begin
    editedItem := e.Item as GridEditableItem;
    var editMan : GridEditManager;
    editMan := editedItem.EditManager;
     
     
   //for each column:GridColumn in e.Item.OwnerTableView.RenderColumns do 
        //begin
            //if (column is IGridEditableColumn) then
                //begin
                    //var str : String;
                    //str := "abc";
                //end;
        //end;
    //
    //var txt := new TextBox;
     
    
    NewValues := new Hashtable;
   
    e.Item.OwnerTableView.ExtractValuesFromItem(NewValues, editedItem);
end;
 
method GridTest.RadGrid1_NeedDataSource(source: System.Object; e: Telerik.Web.UI.GridNeedDataSourceEventArgs);
var SubnetData : DataTable;
begin
  //if Boolean(Session['LoggedIn']) then
       
            //FGridHelper.OpenGrid(FTreeHelper.GetNodeData(tvSubnets.SelectedNode).NodeType,
                           //FTreeHelper.GetNodeData(tvSubnets.SelectedNode).AutonomousNetworkId,
                           //FTreeHelper.GetNodeData(tvSubnets.SelectedNode).SubnetId);
     // When we require to pass field id than we have to use this method and remove comment.
            // FGridHelper.OpenGrid(RadTextBox2.Text.Trim,hdnSearchText.Value.ToUpper,getUserTableID(hdnSearchText.Value.ToUpper),GetOption(hdnSearchMethod.Value),GetFieldId(hdnFieldList.Value.ToString()));
            // Bind grid for right side search
            //FGridHelper.OpenGrid( ("","SUBNET","SUBNET","",nil);
            FGridHelper.OpenGrid("","ADDRESSES",2,EasyIPLibrary_Intf.TSearchOption.soContains,nil)
    
    
end;

Class Flle

TGridHelper = public class
  private
    FGridView: RadGrid;
    FEasyIPConnection: TClientConnection;
    FTableType: TTableType;
    FDataset: DataSet;
    FDatatable: DataTable;
    FSession: HttpSessionState;
 
    method FGridView_UpdateCommand(source: Object; e: GridCommandEventArgs);
    procedure DeleteCommand(source: System.Object; e: GridCommandEventArgs);
    method FGridView_DeleteCommand(source: Object; e: GridCommandEventArgs);
    method ItemDataBound(sender: System.Object; e: Telerik.Web.UI.GridItemEventArgs);
    function AddNewColumn(FieldName, HeaderText: String; IsReadOnly: Boolean): GridBoundColumn;
    method CreateColumnEditor(sender: System.Object; e: Telerik.Web.UI.GridCreateColumnEditorEventArgs);
    method ItemCreated(sender: System.Object; e: Telerik.Web.UI.GridItemEventArgs);
    method ItemCommand(sender: System.Object; e: Telerik.Web.UI.GridCommandEventArgs);
    method UpdateCommand(sender: System.Object; e: Telerik.Web.UI.GridCommandEventArgs);
    method ItemUpdated(sender: System.Object; e: Telerik.Web.UI.GridUpdatedEventArgs);
 
    property Session: HttpSessionState read FSession;
  protected
  public
    constructor(EasyIPConnection: TClientConnection; Grid: RadGrid; ASession: HttpSessionState);
 
    method OpenGrid(NodeType: TNodeType; AutonomousNetworkId, SubnetId: Int64);
    method OpenGrid(const SearchText: String; const TableName: String; TableId: Int64; SearchOption: TSearchOption; FieldIds: Array of System.Int64);
    method OpenGrid(const TableName: String);
    method OpenGrid;
    method UpdateCommand(source: System.Object; e: Telerik.Web.UI.GridUpdatedEventArgs);
    method CloseGrid;
  end;
 
implementation
 
const
  ImageInfoField = '_IMAGE_INFO_FIELD_';
 
constructor TGridHelper(EasyIPConnection: TClientConnection; Grid: RadGrid; ASession: HttpSessionState);
begin
  FEasyIPConnection := EasyIPConnection;
  FSession := ASession;
 
  FGridView := Grid;
 
  FGridView.ItemDataBound += @ItemDataBound;
  FGridView.ItemUpdated += @UpdateCommand;
  FGridView.DeleteCommand += @DeleteCommand;
  FGridView.CreateColumnEditor += @CreateColumnEditor;
  FGridView.ItemCommand += @ItemCommand;
  FGridView.UpdateCommand += @UpdateCommand;
   
end;
 
function TGridHelper.AddNewColumn(FieldName, HeaderText: String; IsReadOnly: Boolean): GridBoundColumn;
begin
  Result := new GridBoundColumn;
  Result.ReadOnly := IsReadOnly;
  Result.HeaderText := HeaderText;
  Result.DataField := FieldName;
   
  Result.HeaderStyle.Wrap := FALSE;
  Result.ItemStyle.Wrap := FALSE;
  Result.UniqueName := FieldName;
 
  if HeaderText = 'Subnet icon' then
    begin
        Result.HeaderText := "";
        Result.HeaderStyle.Width := 30;
        Result.ItemStyle.HorizontalAlign := Result.ItemStyle.HorizontalAlign.Center;
        Result.Resizable := false;
        Result.Reorderable := false;
    end
  else
    Result.HeaderStyle.Width := 350;
 
  FGridView.MasterTableView.Columns.Add(Result);
end;
 
method TGridHelper.ItemDataBound(sender: System.Object; e: Telerik.Web.UI.GridItemEventArgs);
var
  AGridItem: GridDataItem;
  AValue: String;
  NormalImageURL, SelectedImageURL: String;
  i: Integer;
  UserField: TUserField;
  LookupItem: TUserFieldLookup;
  Column: GridBoundColumn;
  ImageInfos: TStringList;
begin
  if e.Item is GridDataItem then
  begin
    AGridItem := GridDataItem(e.Item);
 
    if FTableType = TTableType.ttSubnets then
    begin
      ImageInfos := new TStringList;
 
      // CIDR_MASK, ADDRESS_COUNT, CHILD_COUNT, ITEM_TYPE, SECONDARY_ITEM_TYPE
      for each s:String in AGridItem[ImageInfoField].Text.Split([',']) do 
        ImageInfos.Add(s);
 
      if ImageInfos.Count = 5 then
      begin
        if ImageInfos[3] = 'G' then
          GetNodeImages(NormalImageURL, SelectedImageURL,
                        TNodeType.ntGroup)
        else
          GetNodeImages(NormalImageURL, SelectedImageURL,
                        TNodeType.ntSubnet,
                        Integer.Parse(ImageInfos[0]),
                        ImageInfos[1] <> '0',
                        ImageInfos[2] <> '0');
 
        AGridItem[ImageInfoField].Text := system.string.format('<img src="{0}" alt="" style="border-width:0px"/>', [NormalImageURL]);
      end
      else
        AGridItem[ImageInfoField].Text := '';
    end;
 
    for i := 0 to pred(FGridView.Columns.Count) do
    begin
      if FGridView.Columns[i] is GridBoundColumn then
      begin
        Column := FGridView.Columns[i] as GridBoundColumn;
 
        UserField := FEasyIPConnection.FindUserField(TableTypeToTableName(FTableType), Column.DataField);
 
        if Assigned(UserField) then
        begin 
          LookupItem := nil;
            
          for LoopLookupItem in UserField.LookupList do
            if LoopLookupItem.Caption = AValue then
            begin
              LookupItem := LoopLookupItem;
 
              Break;
            end;
 
          if Assigned(LookupItem) then
          begin
            if LookupItem.Description <> '' then
              AGridItem.Cells[i].Text := LookupItem.Description;
 
            if LookupItem.FontColour <> nil then
              AGridItem.Cells[i].ForeColor := GetWebColor(Integer(LookupItem.FontColour));
 
            if LookupItem.BackgroundColour <> nil then
              AGridItem.Cells[i].BackColor := GetWebColor(Integer(LookupItem.BackgroundColour));
 
            AGridItem.Cells[i].Font.Bold := LookupItem.FontBold;
            AGridItem.Cells[i].Font.Underline := LookupItem.FontUnderline;
            AGridItem.Cells[i].Font.Italic := LookupItem.FontItalic;
          end
          else
          begin
            if UserField.BackgroundColour <> nil then
              AGridItem.Cells[i].BackColor := GetWebColor(Integer(UserField.BackgroundColour));
 
            if UserField.FontColour <> nil then
              AGridItem.Cells[i].ForeColor := GetWebColor(Integer(UserField.FontColour));
 
            AGridItem.Cells[i].Font.Bold := UserField.FontBold;
            AGridItem.Cells[i].Font.Underline := UserField.FontUnderline;
            AGridItem.Cells[i].Font.Italic := UserField.FontItalic;
          end;
        end;
      end;
    end;
  end;
end;
 
method TGridHelper.UpdateCommand(source: System.Object; e: Telerik.Web.UI.GridUpdatedEventArgs);
var
  EditedItem: GridEditableItem;
  SubnetId, KeyValue: Int64;
  NewValues: Hashtable;
  FieldNames: List<String>;
  FieldValues: List<Object>;
  TableName: String;
  i: Integer;
begin
  EditedItem := e.Item as GridEditableItem;
 
  KeyValue := Int64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]['ID']);
 
  NewValues := Hashtable.Create;
  FieldNames := new List<String>;
  FieldValues := new List<Object>;
 
  //The GridTableView will fill the values from all editable columns in the hash
  e.Item.OwnerTableView.ExtractValuesFromItem(NewValues, EditedItem);
   
  for Entry:KeyValuePair<String, Object> in NewValues do
  begin
    FieldNames.Add(Entry.Key.ToString);
    FieldValues.Add(Entry.Value);
  end;
 
  case FTableType of
    TTableType.ttAddresses: TableName := 'ADDRESSES_USER_DATA';
    TTableType.ttSubnets: TableName := 'SUBNETS_USER_DATA';
  end; // case
 
 FEasyIPConnection.UpdateUserFields(TableName, KeyValue, FieldNames.ToArray, FieldValues.ToArray);
 (*   ChangedRow := ChangedRows[0];
    ChangedRow.BeginEdit;
 
    ATransaction := nil;
    try
      for Entry in newValues do
      begin
        FieldPropertiesItem := SessionHelper.FieldPropertiesList.GetFieldPropertiesItem(Session['TableName'].ToString, Entry.Key.ToString);
 
        if (Assigned(FieldPropertiesItem)) and (FieldPropertiesItem.Mandatory) and ((not Assigned(Entry.Value)) or (Entry.Value.ToString = '')) then
          raise EEasyIPError.Create(system.string.Format(GetLocalisationString(105), [Entry.Key.ToString]));
 
        if not Assigned(entry.Value) then // Null cannot be assigned to ChangedRow
          ChangedRow[entry.Key.ToString] := DBNULL.Value
        else
        try
          ChangedRow[entry.Key.ToString] := entry.Value;
        except
          raise EEasyIPError.Create(system.string.format(GetLocalisationString(28), [entry.Value, entry.Key.ToString]));
        end;
 
        if SetSQL <> '' then
          SetSQL := concat(SetSQL, ',');
 
        SetSQL := system.string.format('{0}"{1}"=@P{2}', [SetSQL, entry.Key.ToString, ParamCounter.ToString]);
        SessionHelper.DBConnection.SQLCommand.Parameters.Add(FBParameter.Create(system.string.format('@P{0}', [ParamCounter.ToString]), ChangedRow[entry.Key.ToString]));
 
        inc(ParamCounter);
      end;
 
      UpdateText := system.string.format(UpdateText, [SetSQL]);
 
      SessionHelper.ExecuteQuery(UpdateText);
 
      ChangedRow.EndEdit;
      SessionHelper.DBConnection.DataSet.AcceptChanges;
      SessionHelper.CommitTransaction;
    except
      on ex:Exception do
      begin
        ChangedRow.CancelEdit;
        e.Canceled := TRUE;
 
        SessionHelper.RollbackTransaction;
 
        With  (e.Item as GridEditFormItem).FindControl('lblUpdateErrorTop') as &Label do
        begin
          Text := SessionHelper.DBConnection.TranslateException(ex);
          Visible := TRUE;
        end;
        With  (e.Item as GridEditFormItem).FindControl('lblUpdateErrorBottom') as &Label do
        begin
          Text := SessionHelper.DBConnection.TranslateException(ex);
          Visible := TRUE;
        end;
      end;
    end;
  end;*)
end;
 
procedure TGridHelper.DeleteCommand(source: System.Object; e: GridCommandEventArgs);
var
  EditedItem: GridEditableItem;
  SubnetId, KeyValue: Int64;
begin
  EditedItem := e.Item as GridEditableItem;
 
  KeyValue := Int64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]['ID']);
  SubnetId := Int64(Session['LastDataGridSubnetId']);
 
  FEasyIPConnection.DeleteIPAddressesById(SubnetId, [KeyValue]);
end;
 
method TGridHelper.CloseGrid;
begin
  FGridView.DataSource := nil;
 
  FGridView.Visible := FALSE;
end;
 
method TGridHelper.OpenGrid(NodeType: TNodeType; AutonomousNetworkId, SubnetId: Int64);
begin
  FDataSet := nil;
 
  FTableType := TTableType.ttSubnets;
 
  case NodeType of
    TNodeType.ntAutonomousNetwork:
      begin
        FDataSet := FEasyIPConnection.GetGridRootNodes(AutonomousNetworkId);
      end;
 
    TNodeType.ntGroupWithChildren,
    TNodeType.ntRestrictedGroupWithChildren,
    TNodeType.ntSubnetWithChildren:
      begin
        FDataSet := FEasyIPConnection.GetGridChildNodes(AutonomousNetworkId, SubnetId);
      end;
 
    TNodeType.ntSubnetWithIPAddresses:
      begin
        FDataSet := FEasyIPConnection.GetGridNodeIPAddresses(SubnetId);
 
        FTableType := TTableType.ttAddresses;
      end;
  end; // case
 
  if Assigned(FDataSet) then
  begin
    FGridView.DataSource := FDataSet;
    FGridView.MasterTableView.DataMember := FDataset.Tables[0].TableName;
    FGridView.Visible := TRUE;
    OpenGrid;
  end
  else
    CloseGrid;
 
  Session['LastDataGridSubnetId'] := SubnetId;
end;
 
method TGridHelper.OpenGrid;
const
  IMAGE_COL_WIDTH = 30;
var
  UserFields: array of TUserField;
  NewButton: GridEditCommandColumn;
  NewGridButtonColumn: GridButtonColumn;
  KeyFieldNames: Array of String;
  i, FixedColCount: Integer;
  VisibleColumnCount, VisibleColumnIndex: Integer;
 
begin
  FGridView.Columns.Clear;
 
  FixedColCount := 0;
  VisibleColumnCount := 0;
 
  SetLength(KeyFieldNames, 1);
  KeyFieldNames[0] := 'ID';
 
  FGridView.MasterTableView.DataKeyNames := KeyFieldNames;
         
  case FTableType of
    TTableType.ttSubnets:
      begin
        FGridView.MasterTableView.EditFormSettings.CaptionDataField := 'SHORT_SUBNET';
        FGridView.MasterTableView.EditFormSettings.CaptionFormatString := 'Subnet: <B>{0}</B>';
      end;
 
    TTableType.ttAddresses:
      begin
        FGridView.MasterTableView.EditFormSettings.CaptionDataField := 'SHORT_IP_ADDRESS';
        FGridView.MasterTableView.EditFormSettings.CaptionFormatString := 'IP Address: <B>{0}</B>';
      end;
  end;
  FGridView.AutoGenerateEditColumn := true;
  FGridView.AllowAutomaticUpdates := false;
  // Create edit button
  NewButton := GridEditCommandColumn.Create;
  FGridView.Columns.Add(NewButton);
  NewButton.ButtonType := Telerik.Web.UI.GridButtonColumnType.ImageButton;
  NewButton.Groupable := FALSE;
  NewButton.HeaderStyle.Width := IMAGE_COL_WIDTH;
  NewButton.Reorderable := FALSE;
  NewButton.Resizable := FALSE;
 
   
 
  Inc(FixedColCount);
 
  // Create delete button
  if FTableType = TTableType.ttAddresses then
  begin
    NewGridButtonColumn := GridButtonColumn.Create;
    FGridView.Columns.Add(NewGridButtonColumn);
    NewGridButtonColumn.CommandName := 'Delete';
    NewGridButtonColumn.ConfirmText := 'Are you sure you want to delete the selected IP address?';
    NewGridButtonColumn.Text := '<img src="./Images/General/Delete.png" alt="x" style="border-width:0px"/>';
    NewGridButtonColumn.HeaderStyle.Width := IMAGE_COL_WIDTH;
    NewGridButtonColumn.Groupable := FALSE;
    NewGridButtonColumn.Reorderable := FALSE;
    NewGridButtonColumn.Resizable := FALSE;
 
    Inc(FixedColCount);
  end;
 
  // Find the fields for the selected table
  UserFields := FEasyIPConnection.GetUserFields(TableTypeToTableName(FTableType));
 
  for UserField in UserFields do
  begin
    if ((UserField.Selectable) and
       (not UserField.HiddenColumn)) or
       ((FTableType = TTableType.ttSubnets) and (UserField.FieldName = ImageInfoField)) then
    begin
      if UserField.FixedColumn then
        Inc(FixedColCount);
 
      if UserField.DisplayName = '' then
        AddNewColumn(UserField.FieldName, Uncapitalise(UserField.FieldName), UserField.ReadOnly)
     else        
        AddNewColumn(UserField.FieldName, UserField.DisplayName, UserField.ReadOnly);
 
      if not UserField.ReadOnly then
        Inc(VisibleColumnCount);
    end;
  end;
 
  FGridView.ClientSettings.Scrolling.FrozenColumnsCount := FixedColCount;
 
  VisibleColumnIndex := 0;
 
  for i := 0  to pred(FGridView.Columns.Count) do
    if (FGridView.Columns[i] is GridBoundColumn) and (GridBoundColumn(FGridView.Columns[i]).Visible) and (not GridBoundColumn(FGridView.Columns[i]).ReadOnly) then
    begin
      GridBoundColumn(FGridView.Columns[i]).EditFormColumnIndex := Trunc((System.Double(FGridView.MasterTableView.EditFormSettings.ColumnNumber) / System.Double(VisibleColumnCount)) * System.Double(VisibleColumnIndex));
 
      Inc(VisibleColumnIndex);
    end
end;
 
method TGridHelper.ItemCreated(sender: System.Object; e: Telerik.Web.UI.GridItemEventArgs);
//var
//  lbl: &Label;
begin
  {if (e.Item is GridEditFormItem) and (e.Item.IsInEditMode) then
  begin
    lbl := &Label.Create;
    lbl.ID := 'lblUpdateErrorTop';
    lbl.Visible := false;
    lbl.CssClass := 'label_error';
    (e.Item as GridEditFormItem).EditFormCell.Controls.AddAt(0, lbl);
 
    lbl := &Label.Create;
    lbl.ID := 'lblUpdateErrorBottom';
    lbl.Visible := false;
    lbl.CssClass := 'label_error';
    (e.Item as GridEditFormItem).EditFormCell.Controls.Add(lbl);
  end;}
end;
 
method TGridHelper.CreateColumnEditor(sender: System.Object; e: Telerik.Web.UI.GridCreateColumnEditorEventArgs);
var
  UserField: TUserField;
  MaxLength: Integer;
  FieldName, Skin: String;
  ARadComboBoxItem: RadComboBoxItem;
  ARadComboBox: RadComboBox;
begin
  if e.Column is GridBoundColumn then
  begin
    MaxLength := 0;
 
    UserField := FEasyIPConnection.FindUserField(TableTypeToTableName(FTableType), (e.Column as GridBoundColumn).DataField);
 
    if Assigned(UserField) then
    begin
      FieldName := (e.Column as GridBoundColumn).DataField.ToString;
 
      MaxLength := UserField.FieldSize;
 
      if UserField.FieldType in [TEIPDataType.edatString, TEIPDataType.edatWideString] then
      begin
        if UserField.LookupType <> TUserFieldLookupType.ltNone then
        begin
          e.ColumnEditor := new TCustomColumnEditor(concat('DropDown_', FieldName), TEditorType.etComboBox);
 
          ARadComboBox := ((e.ColumnEditor as TCustomColumnEditor).EditControl as RadComboBox);
          ARadComboBox.AllowCustomText := UserField.LookupType = TUserFieldLookupType.ltEditable;
 
          ARadComboBox.Items.Clear;
 
          for LookupItem in UserField.LookupList do
          begin
            ARadComboBoxItem := new RadComboBoxItem;
 
            ARadComboBoxItem.Value := LookupItem.Caption;
            ARadComboBoxItem.Text := LookupItem.Caption;
 
            if LookupItem.FontColour <> nil then
              ARadComboBoxItem.ForeColor := GetWebColor(Integer(LookupItem.FontColour));
 
            if LookupItem.BackgroundColour <> nil then
              ARadComboBoxItem.BackColor := GetWebColor(Integer(LookupItem.BackgroundColour));
 
            ARadComboBoxItem.Font.Bold := LookupItem.FontBold;
            ARadComboBoxItem.Font.Underline := LookupItem.FontUnderline;
            ARadComboBoxItem.Font.Italic := LookupItem.FontItalic;
 
            ARadComboBox.Items.Add(ARadComboBoxItem);
          end;
 
          ARadComboBoxItem := RadComboBoxItem.Create;
          ARadComboBoxItem.Value := '';
          ARadComboBoxItem.Text := '[Blank]';
           
          ARadComboBox.Items.Add(ARadComboBoxItem);
 
          ARadComboBox.MaxLength := MaxLength;
        end
        else
        if UserField.EditMask <> '' then
        begin
          e.ColumnEditor := new TCustomColumnEditor(concat('MaskEdit_', FieldName), TEditorType.etMaskedText);
          ((e.ColumnEditor as TCustomColumnEditor).EditControl as RadMaskedTextBox).Mask := UserField.EditMask;
          ((e.ColumnEditor as TCustomColumnEditor).EditControl as RadMaskedTextBox).MaxLength := MaxLength;
        end
        else
        begin
          e.ColumnEditor := new TCustomColumnEditor(concat('Edit_', FieldName), TEditorType.etText);
          ((e.ColumnEditor as TCustomColumnEditor).EditControl as RadTextBox).MaxLength := MaxLength;         
        end;
      end else
      begin
        if UserField.FieldType in [TEIPDataType.edatWideMemo, TEIPDataType.edatMemo] then
           e.ColumnEditor := new TCustomColumnEditor(concat('TextBox_', FieldName), TEditorType.etMemo, Skin);
      end;
       
    end;
  end;
end;
 
 
method TGridHelper.FGridView_DeleteCommand(source: Object; e: GridCommandEventArgs);
begin
end;
 
method TGridHelper.OpenGrid(const SearchText: String; const TableName: String; TableId: Int64; SearchOption: TSearchOption; FieldIds: Array of System.Int64);
begin
  if TableName = 'SUBNETS' then
    begin
        FTableType := TTableType.ttSubnets;
        FDatatable := FEasyIPConnection.SearchTableBasic(TableId,SearchText,SearchOption,FieldIds);
    end
  else
  if TableName = 'ADDRESSES' then
    begin
        FTableType := TTableType.ttAddresses;
        FDatatable := FEasyIPConnection.SearchTableBasic(TableId,SearchText,SearchOption,FieldIds);
    end
  else
  if TableName = 'GLOBAL ARP TABLE' then
    begin
        FDatatable := FEasyIPConnection.SearchARPEntries(SearchText);
    end
  else
    begin
    // raise error
    end;
 
  // Load FDataset here (FDataset := FEasyIPConnection.SearchTableBasic(....
   
  if FDatatable <> nil then
  begin
    FGridView.DataSource := FDatatable;
    FGridView.MasterTableView.DataMember := FDatatable.TableName;
    FGridView.Visible := TRUE;
    OpenGrid;
  end;
   
end;
 
method TGridHelper.OpenGrid(const TableName: String);
begin
    FGridView.DataSource := FEasyIPConnection.GetUserFields(TableName.ToUpper());;;
    FGridView.MasterTableView.DataMember := FDatatable.TableName;
    FGridView.Visible := TRUE;
    OpenGrid;
   
end;
 
method TGridHelper.ItemCommand(sender: System.Object; e: Telerik.Web.UI.GridCommandEventArgs);
begin
  if e.CommandName = RadGrid.EditCommandName then
     begin
        //OpenGrid;
     end;
  if e.CommandName = RadGrid.InitInsertCommandName then
       FGridView.MasterTableView.ClearEditItems(); 
  if e.CommandName = RadGrid.UpdateCommandName then
    begin
       //UpdateCommand(sender,e);
       //var str : String;
       //str := "Update"
    end        
end;
 
method TGridHelper.ItemUpdated(sender: System.Object; e: Telerik.Web.UI.GridUpdatedEventArgs);
  var
  EditedItem: GridEditableItem;
begin
   EditedItem := e.Item as GridEditableItem;
end;
 
method TGridHelper.UpdateCommand(sender: System.Object; e: Telerik.Web.UI.GridCommandEventArgs);
var
  EditedItem: GridEditableItem;
  Item : GridEditFormItem;
  SubnetId, KeyValue: Int64;
  NewValues: Hashtable;
  FieldNames: List<String>;
  FieldValues: List<Object>;
  TableName,PlantName: String;
  i: Integer;
begin
   
  EditedItem := e.Item as GridEditableItem;
  FGridView.MasterTableView.ClearEditItems();
  KeyValue := Int64(e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]['ID']);
 
  NewValues := new Hashtable;
  FieldNames := new List<String>;
  FieldValues := new List<Object>;
  if e.Item.IsInEditMode = true then
  begin
    var str : String;
    str := "Edit";
  end;
  //The GridTableView will fill the values from all editable columns in the hash
   
  e.Item.OwnerTableView.ExtractValuesFromItem(NewValues, EditedItem);
  var IPAddress : String;
  IPAddress := (editedItem["Location"].Controls[1] as TextBox).Text;
     
 for Entry:DictionaryEntry in NewValues do
        begin
            FieldNames.Add(Entry.Key.ToString);
            FieldValues.Add(Entry.Value);
        end;
  case FTableType of
    TTableType.ttAddresses: TableName := 'ADDRESSES_USER_DATA';
    TTableType.ttSubnets: TableName := 'SUBNETS_USER_DATA';
  end; // case
 
 FEasyIPConnection.UpdateUserFields(TableName, KeyValue, FieldNames.ToArray, FieldValues.ToArray);
 (*   ChangedRow := ChangedRows[0];
    ChangedRow.BeginEdit;
 
    ATransaction := nil;
    try
      for Entry in newValues do
      begin
        FieldPropertiesItem := SessionHelper.FieldPropertiesList.GetFieldPropertiesItem(Session['TableName'].ToString, Entry.Key.ToString);
 
        if (Assigned(FieldPropertiesItem)) and (FieldPropertiesItem.Mandatory) and ((not Assigned(Entry.Value)) or (Entry.Value.ToString = '')) then
          raise EEasyIPError.Create(system.string.Format(GetLocalisationString(105), [Entry.Key.ToString]));
 
        if not Assigned(entry.Value) then // Null cannot be assigned to ChangedRow
          ChangedRow[entry.Key.ToString] := DBNULL.Value
        else
        try
          ChangedRow[entry.Key.ToString] := entry.Value;
        except
          raise EEasyIPError.Create(system.string.format(GetLocalisationString(28), [entry.Value, entry.Key.ToString]));
        end;
 
        if SetSQL <> '' then
          SetSQL := concat(SetSQL, ',');
 
        SetSQL := system.string.format('{0}"{1}"=@P{2}', [SetSQL, entry.Key.ToString, ParamCounter.ToString]);
        SessionHelper.DBConnection.SQLCommand.Parameters.Add(FBParameter.Create(system.string.format('@P{0}', [ParamCounter.ToString]), ChangedRow[entry.Key.ToString]));
 
        inc(ParamCounter);
      end;
 
      UpdateText := system.string.format(UpdateText, [SetSQL]);
 
      SessionHelper.ExecuteQuery(UpdateText);
 
      ChangedRow.EndEdit;
      SessionHelper.DBConnection.DataSet.AcceptChanges;
      SessionHelper.CommitTransaction;
    except
      on ex:Exception do
      begin
        ChangedRow.CancelEdit;
        e.Canceled := TRUE;
 
        SessionHelper.RollbackTransaction;
 
        With  (e.Item as GridEditFormItem).FindControl('lblUpdateErrorTop') as &Label do
        begin
          Text := SessionHelper.DBConnection.TranslateException(ex);
          Visible := TRUE;
        end;
        With  (e.Item as GridEditFormItem).FindControl('lblUpdateErrorBottom') as &Label do
        begin
          Text := SessionHelper.DBConnection.TranslateException(ex);
          Visible := TRUE;
        end;
      end;
    end;
  end;*)
end;
 
method TGridHelper.FGridView_UpdateCommand(source: Object; e: GridCommandEventArgs);
begin
end;

On RadGrid1_UpdateCommand method when i try to get new values i got an error.

e.Item.OwnerTableView.ExtractValuesFromItem(NewValues, editedItem); --- Here i got an error.

Here i am also attache scree shot of trace value.
0
Marin
Telerik team
answered on 26 Nov 2010, 11:40 AM
Hello Kaushal,

The problem is in the following line;
e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]['ID']

In order to use the DataKeyValues collection you should have set the DataKeyNames property of the grid first. You can do it the following way:
 
<telerik:radgrid id="RadGrid1" runat="server" onneeddatasource="RadGrid1_NeedDataSource" DataKeyNames="ID" ...>

The property should be set to an existing field from your datasource. You can get more information from this help topic.

Best wishes,
Marin
the Telerik team
Browse the vast support resources we have to jumpstart your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
Kaushal
Top achievements
Rank 1
answered on 26 Nov 2010, 01:02 PM
Hi Marin ,
 
             Thanks for your reply, i have already set DataKeyNames for grid in class file i had highlight that code also,please check once if i did anything wrong. and in updatemetho i didn't get erron to fetch datakey value but i got an error on

e.Item.OwnerTableView.ExtractValuesFromItem(NewValues, editedItem);



Please i couldn't understand and catch the sily mistakes as i did in my code and what is the reason behind this error.

Thanks
Kaushal
0
Marin
Telerik team
answered on 02 Dec 2010, 03:04 PM
Hello Kaushal,

I see you set the DataKeyNames and add columns to the grid in the needDataSource event. This is not recommended approach, you should use the Page_Init or Page_Load events to add columns programmatically to the grid. NeedDatasource event should be used only to set the datasource property for the grid. You can check this help article for further information on how to add programmatically columns to the grid. 

Also have you tried setting the datakeyNames in the markup for the grid since they always have the same value ("ID"). Moreover in the UpdateCommand event handler for the grid you can check whether the EditedItem  variable has all the expected column (use editedItem["ColumnUniqueName"] ). Also when you perform custom update/insert/delete command you do not need this setting allowautomaticupdates="true" in the markup for the grid. It is required only if you leave the DataSource to perform the update operation automatically. Additionally you can first manually try getting the value for all the column (editedColumn["columnUniqueName"].Text) to see if all columns are accessible correctly and if so you can try calling the ExtractValueFromItem method.

Hope this helps.

All the best,
Marin
the Telerik team
Browse the vast support resources we have to jumpstart your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.
0
Nguyen Anh Tai
Top achievements
Rank 1
answered on 16 Aug 2011, 09:38 AM
Hi all,

I have tried to use extractOldValuesFromItem and extractValuesFromItem methods in client code (javascript) based on help from Telerik official sites (http://www.telerik.com/help/aspnet-ajax/grid-gridtableview-extractvaluesfromitem.html and http://www.telerik.com/help/aspnet-ajax/grid-gridtableview-extractoldvaluesfromitem.html)
and they seem doesn't work as expected. 

I receive "'id' is null or not an object" exception and some time null object, although there is data in my grid.

Could you provide me a running sample of using CLIENT extractOldValuesFromItem and extractValuesFromItem methods of masterTableView client object?

I already set DataKeyNames property of the grid. But my key field has different name than ID. Does it cause any trouble?



 

0
Mira
Telerik team
answered on 19 Aug 2011, 08:55 AM
Hello Nguyen Anh Tai,

Please refer to this forum post for the answers to your questions.

In order to avoid duplicate posts, I suggest that we continue the communication in the other thread if necessary.

Regards,
Mira
the Telerik team

Browse the vast support resources we have to jump start your development with RadControls for ASP.NET AJAX. See how to integrate our AJAX controls seamlessly in SharePoint 2007/2010 visiting our common SharePoint portal.

Tags
Grid
Asked by
Kaushal
Top achievements
Rank 1
Answers by
Marin
Telerik team
Kaushal
Top achievements
Rank 1
Nguyen Anh Tai
Top achievements
Rank 1
Mira
Telerik team
Share this question
or