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

RadGrid Edit inLine Validators

1 Answer 36 Views
Grid
This is a migrated thread and some comments may be shown as answers.
July
Top achievements
Rank 2
July asked on 02 Nov 2011, 06:04 PM
I attach my Grid.
I've a several button such as:
Quick Add (add new record in line)
Full Add/Full Edit(open a radwindos)
quickEdit (Edit Inline)

I add Vallidators programmatically (I paste my code at last)

I've 2 problems:

1) If I Edit validations works perfect, but for QUICK ADD (add inline) does not work,
2) RadWindows.CONFIRM (I need catch ths button clicked, IF is OK --> I need remove community and if IF cancel I can't remove)

I USE MASTER/DETAILS

ASPX CODE

  <telerik:RadGrid ID="RadGrid1" runat="server" OnNeedDataSource="RadGrid1_NeedDataSource"
                AllowPaging="True" AllowSorting="True" OnDeleteCommand="RadGrid1_DeleteCommand"
                 AllowFilteringByColumn="True" OnUpdateCommand="RadGrid1_UpdateCommand" OnInsertCommand="RadGrid1_InsertCommand"
                Width="99.8%" PageSize="12" Height="500px" AutoGenerateColumns="False" CellSpacing="0" OnItemCommand="RadGrid1_ItemCommand"
                         
                 GridLines="None" OnPreRender="RadGrid1_PreRender" OnItemCreated="RadGrid1_ItemCreated">

                  <MasterTableView DataKeyNames="Id" CommandItemDisplay="Top"
                    EditMode="InPlace" TableLayout="Fixed" >
                    
                    <Columns>
                         <telerik:GridTemplateColumn UniqueName="TemplateEditColumn"  HeaderStyle-Width="3%"  AllowFiltering="false">
                        <ItemTemplate>
                            <asp:ImageButton ID="EditLink" runat="server"   ImageUrl="~/UI/Images/pencil.png" ></asp:ImageButton>
                        </ItemTemplate>
                    </telerik:GridTemplateColumn>
                      <telerik:GridEditCommandColumn HeaderStyle-Width="3%" UniqueName="EditCommandColumn"
                        ButtonType="ImageButton" EditImageUrl="../Images/grid_edit.png">
                    </telerik:GridEditCommandColumn>  
                   
                        <telerik:GridButtonColumn UniqueName="btnDelete" ConfirmDialogType="RadWindow"
                            ButtonType="ImageButton" CommandName="Delete" ConfirmDialogHeight="100px" ConfirmDialogWidth="300px"
                            HeaderStyle-Width="3%" />
                        <telerik:GridTemplateColumn DataField="Id" HeaderText="Id" UniqueName="Id" Visible="false">
                            <InsertItemTemplate>
                                <telerik:RadTextBox ID="RadTextBox1" runat="server" Text='<%# Bind("Id") %>' Width="150px"
                                    ReadOnly="true" Enabled="false" />
                            </InsertItemTemplate>
                            <EditItemTemplate>

                                <telerik:RadTextBox ID="RadTextBox1" runat="server" Text='<%# Eval("Id") %>' ReadOnly="true"
                                    Width="150px" />
                            </EditItemTemplate>
                        </telerik:GridTemplateColumn>
                        <telerik:GridBoundColumn DataField="Name" UniqueName="Name" ColumnEditorID="editorName" />
                        <telerik:GridBoundColumn DataField="Description" UniqueName="Description" ColumnEditorID="editorDescription"  />                       
                    </Columns>
                   
                      <CommandItemTemplate>
                        <div style="width: 100%">
                            <div style="width: 10%; margin-left: 12px; float: left">
                             <asp:LinkButton ID="LinkButton2" runat="server" CommandName="InitInsert" ><asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="~/UI/Images/add.png" /> <asp:Label ID="lblQuickAdd" runat="server" /></asp:LinkButton>&nbsp;&nbsp; </div><div style="width: 10%; float: left">
                                <a href="#" onclick="return ShowInsertForm();">
                                    <asp:ImageButton ID="imgAddFull" runat="server" ImageUrl="~/UI/Images/add.png" />
                                    <asp:Label ID="lblFullAdd" runat="server" />
                                </a>
                            </div>
                        </div>
                    </CommandItemTemplate>
                         
                
                 
                         </MasterTableView>    
                           <PagerStyle Mode="NumericPages" />
            </telerik:RadGrid>
          <telerik:GridTextBoxColumnEditor ID="editorName" runat="server" TextBoxStyle-Width="200px" />             
            <telerik:GridTextBoxColumnEditor ID="editorDescription" runat="server" TextBoxStyle-Width="200px" />  
         <telerik:RadWindowManager ID="RadWindowManager1" runat="server" EnableShadow="true">

CS CODE

using System;
using System.Collections;
using System.Globalization;
using System.Resources;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using WebSearch.Components;
using WebSearch.Log;
using WebSearch.SecurityModel;


namespace WebSearch.UI.Admin
{
    public partial class UserManagement : System.Web.UI.Page
    {
      #region Properties&Variables
        private Organization _organization;
        private string _culture;
        private ResourceManager _resources;
      #endregion

      #region Events

      protected void Page_Load(object sender, EventArgs e)
      {
          GetInfo();
          
            if(!Page.IsPostBack)
            {
                LoadSettings();
               
            }
        }

     protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
      {
            LoadData();
      }

      protected void RadGrid1_PreRender(object sender, EventArgs e)
      {
       
        RadGrid1.MasterTableView.GetColumnSafe("RowIndicator").Display = false;
        RadGrid1.MasterTableView.GetColumnSafe("IsSuper").Display = App.CurrentUserIsSuper();
        
     
        CommonFunctions.RemoveFilterOptions(RadGrid1);
      }

      protected void RadGrid1_InsertCommand(object sender, GridCommandEventArgs e)
      {
          if (!Page.IsValid) return;

          GridEditableItem item = e.Item as GridEditableItem;
          if (item != null)
          {
              
              Hashtable values = new Hashtable();
              item.ExtractValues(values);

              _organization = new Organization
              {
                  User = new User
                  {
                      FirstName = values["FirstName"] == null ? null : values["FirstName"].ToString(),
                      MiddleName = values["MiddleName"] == null ? null : values["MiddleName"].ToString(),
                      LastName = values["LastName"] == null ? null : values["LastName"].ToString(),
                      Address = values["Address"] == null ? null : values["Address"].ToString(),
                      Phone = values["Phone"] == null ? null : values["Phone"].ToString(),
                      CellPhone = values["CellPhone"] == null ? null : values["CellPhone"].ToString(),
                      ExternalId = values["ExternalId"] == null ? null : values["ExternalId"].ToString(),
                      Loginid = values["LoginId"] == null ? null : values["LoginId"].ToString(),
                      Email = values["Email"] == null ? null : values["Email"].ToString(),
                      IsSuper = values["IsSuper"] == null ? false : Convert.ToBoolean(values["IsSuper"]),
                  }

              }
          ;


              try
                {
                    _organization.CreateUser();

                  
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }


             
          }
        }

     protected void RadGrid1_DeleteCommand(object sender, GridCommandEventArgs e)
      {
          var userId = (e.Item as GridDataItem).GetDataKeyValue("Id").ToString();

          _organization = new Organization
          {
            User = new User() { Id = Convert.ToInt16(userId) }
          };

        if ( _organization.IsSuperUser(Convert.ToInt16(userId) ))
        {
            if (_organization.IsUniqueSuper())
            {
                RadWindowManager1.RadAlert(_resources.GetString("ErrorDelete", new CultureInfo(_culture)), 330, 100, _resources.GetString("ErrorTitleDelete", new CultureInfo(_culture)), "");

//TODO: IF OK IS CLICKED REMOVE COMMUNITY
            }

        }

         else
          {
              _organization.RemoveUser();
          }


         
      }

      protected void RadGrid1_UpdateCommand(object sender, GridCommandEventArgs e)
      {
          if (!Page.IsValid) return;

          GridEditableItem item = e.Item as GridEditableItem;
          if (item != null)
          {
              var userId = item.GetDataKeyValue("Id");
              Hashtable values = new Hashtable();
              item.ExtractValues(values);

                  _organization = new Organization
            {
                User = new User
                {
                  
                                      Id = Convert.ToInt16(userId),
                                      FirstName = values["FirstName"] == null ? null : values["FirstName"].ToString(),
                                      MiddleName = values["MiddleName"] == null ? null : values["MiddleName"].ToString(),
                                      LastName = values["LastName"] == null ? null : values["LastName"].ToString(),
                                      Address = values["Address"] == null ? null : values["Address"].ToString(),
                                      Phone = values["Phone"] == null ? null : values["Phone"].ToString(),
                                      CellPhone = values["CellPhone"] == null ? null : values["CellPhone"].ToString(),
                                      ExternalId = values["ExternalId"] == null ? null : values["ExternalId"].ToString(),
                                      Loginid = values["LoginId"] == null ? null : values["LoginId"].ToString(),
                                      Email = values["Email"] == null ? null : values["Email"].ToString(),
                                      IsSuper = values["IsSuper"] == null ? false :Convert.ToBoolean(values["IsSuper"]),
                                      }
                                          
          }
              ;

              _organization.quick = true;
              _organization.UpdateUser();

          }
      }

      protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
      {
          if (e.Argument == "Rebind")
          {
              RadGrid1.MasterTableView.SortExpressions.Clear();
              RadGrid1.MasterTableView.GroupByExpressions.Clear();
              RadGrid1.Rebind();
          }
          else if (e.Argument == "RebindAndNavigate")
          {
              RadGrid1.MasterTableView.SortExpressions.Clear();
              RadGrid1.MasterTableView.GroupByExpressions.Clear();
              RadGrid1.MasterTableView.CurrentPageIndex = RadGrid1.MasterTableView.PageCount - 1;
              RadGrid1.Rebind();
          }
      }


      protected void RadGrid1_ItemUpdated(object source, Telerik.Web.UI.GridUpdatedEventArgs e)
      {
          GridEditableItem item = (GridEditableItem)e.Item;
        
          if (e.Exception != null)
          {
              e.KeepInEditMode = true;
              e.ExceptionHandled = true;
             
          }
         
      }

      protected void RadGrid1_ItemInserted(object source, GridInsertedEventArgs e)
      {
          if (e.Exception != null)
          {
              e.ExceptionHandled = true;
             
          }
         
      }

      protected void RadGrid1_ItemDeleted(object source, GridDeletedEventArgs e)
      {
          GridDataItem dataItem = (GridDataItem)e.Item;
        

          if (e.Exception != null)
          {
              e.ExceptionHandled = true;
             
          }
        
      }

     

      protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
      {
          
              if (_resources == null || _culture == null) GetInfo();

            

              GridCommandItem item = e.Item as GridCommandItem;
              if (item != null)
              {
                  ((Label)item.FindControl("lblQuickAdd")).Text = _resources.GetString("lblQuickAdd", new CultureInfo(_culture));
                  ((Label)item.FindControl("lblFullAdd")).Text = _resources.GetString("lblFullAdd", new CultureInfo(_culture));
              }

              if (e.Item is GridDataItem)
              {
                  if (e.Item.ItemIndex < 0) return;

                  ImageButton editLink = (ImageButton)e.Item.FindControl("EditLink");
                  editLink.AlternateText = _resources.GetString(editLink.ID, new CultureInfo(_culture));
                  editLink.Attributes["href"] = "#";

                  editLink.Attributes["onclick"] = String.Format("return ShowEditForm('{0}','{1}');", e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"], e.Item.ItemIndex);
              }

          /*validations*/

    

              if ((e.Item is GridEditableItem && e.Item.IsInEditMode) )
              {
                  for (int i =2; i < RadGrid1.MasterTableView.Columns.Count; i++ )
                      {
                          if (RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "firstname" ||
                              RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "lastname" ||
                              RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "loginid" ||
                              RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "email")
                              AddRequiredValidator(RadGrid1.MasterTableView.Columns[i].UniqueName, e);

                          if (RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "email" ||
                              RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "loginid")
                              AddCustomValidator(RadGrid1.MasterTableView.Columns[i].UniqueName, e);

                       if (RadGrid1.MasterTableView.Columns[i].IsEditable && RadGrid1.MasterTableView.Columns[i].UniqueName.ToLower() == "email")
                           AddExpressRegularEmail(RadGrid1.MasterTableView.Columns[i].UniqueName, e);
                      }

              }

              if (e.Item is GridDataItem && e.Item.IsInEditMode)
              {
                  GridDataItem itemc = (GridDataItem)e.Item;
                  CheckBox chkbox = (CheckBox)itemc["IsSuper"].Controls[0];
                  chkbox.Enabled = true;
              }

      }

      protected void RadGrid1_ItemCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
    {
        if (e.CommandName == RadGrid.EditCommandName)
        {
            Session["ID"] = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["Id"];
        }


        if (e.CommandName == RadGrid.InitInsertCommandName) //"Quick add new" button clicked
        {

            GridTemplateColumn fulledit = (GridTemplateColumn)RadGrid1.MasterTableView.GetColumn("TemplateEditColumn");
            fulledit.Visible = false;
        }
        else if (e.CommandName == RadGrid.RebindGridCommandName && e.Item.OwnerTableView.IsItemInserted)
        {
            e.Canceled = true;
        }
        else
        {
            GridTemplateColumn fulledit = (GridTemplateColumn)RadGrid1.MasterTableView.GetColumn("TemplateEditColumn");
            if (!fulledit.Visible)
                fulledit.Visible = true;

        }

       
    }

      protected void cvLoginId_ServerValidate(object sender, ServerValidateEventArgs e)
      {
          _organization = new Organization();
          e.IsValid = !_organization.ExistLogin(e.Value.ToString(), GetId());
      }

      protected void cvEmail_ServerValidate(object sender, ServerValidateEventArgs e)
      {
          _organization = new Organization();
          e.IsValid = !_organization.ExistEmail(e.Value.ToString(), GetId());
      }
      #endregion


      #region Methods

      private void AddCustomValidator(string colName, GridItemEventArgs e)
      {
             GridEditableItem itemEditable = e.Item as GridEditableItem;

             if (itemEditable != null)
             {
                 GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)itemEditable.EditManager.GetColumnEditor(colName);
                 TableCell cell = (TableCell)editor.TextBoxControl.Parent;

                 CustomValidator validator = new CustomValidator();
                 editor.TextBoxControl.ID = colName;
                 validator.ControlToValidate = editor.TextBoxControl.ID;
                 validator.CssClass = "validator";
                 validator.Display = ValidatorDisplay.Dynamic;
                 validator.ErrorMessage = _resources.GetString("cv"+colName, new CultureInfo(_culture));
                 if (colName.ToLower() == "email")
                     validator.ServerValidate += cvEmail_ServerValidate;
                 if (colName.ToLower() == "loginid")
                    validator.ServerValidate += cvLoginId_ServerValidate;
                 cell.Controls.Add(validator);
             }
         }

      private int GetId()
      {
          return Convert.ToInt16(Session["ID"] ?? 0);
      }

      private void AddExpressRegularEmail(string colName, GridItemEventArgs e){

           GridEditableItem itemEditable = e.Item as GridEditableItem;
         if (itemEditable != null)
          {
              GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)itemEditable.EditManager.GetColumnEditor(colName);
              TableCell cell = (TableCell)editor.TextBoxControl.Parent;

              RegularExpressionValidator validator = new RegularExpressionValidator();
              editor.TextBoxControl.ID = colName;
              validator.ControlToValidate = editor.TextBoxControl.ID;
              validator.CssClass = "validator";
              validator.Display = ValidatorDisplay.Dynamic;
              validator.ErrorMessage = _resources.GetString("revEmail", new CultureInfo(_culture));
              validator.ValidationExpression = @"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$";
              cell.Controls.Add(validator);
          }
         
        }

      private void AddRequiredValidator( string colName, GridItemEventArgs e)
        {
           GridEditableItem itemEditable = e.Item as GridEditableItem;
          if (itemEditable == null) return;

          GridTextBoxColumnEditor editor = (GridTextBoxColumnEditor)itemEditable.EditManager.GetColumnEditor(colName);
          TableCell cell = (TableCell)editor.TextBoxControl.Parent;

          RequiredFieldValidator validator = new RequiredFieldValidator();
          editor.TextBoxControl.ID = colName;
          validator.ControlToValidate = editor.TextBoxControl.ID;
          validator.CssClass = "validator";
          validator.Display = ValidatorDisplay.Dynamic;
          validator.ErrorMessage = "*";
          cell.Controls.Add(validator);
        }


       private void LoadData()
         {
          _organization = new Organization();

          try
          {
            RadGrid1.DataSource = _organization.GetUsersOfOrganization();
          }
          catch (Exception ex)
          {
            WriterLog.WriterinlogFil(ex);
            throw new Exception(ex.ToString());
          }
        }

      private  void LoadSettings()
      {
        if (_resources == null || _culture == null) GetInfo();
             
        RadGrid1.MasterTableView.EditFormSettings.InsertCaption = _resources.GetString("insertCaption", new CultureInfo(_culture));

             
        string type = Request.QueryString["Type"] ;
        if (string.IsNullOrEmpty(type)) type = "List";

        SetTitle("lblTitileList");  

       

        RadGrid1.MasterTableView.GetColumnSafe("FirstName").HeaderText = _resources.GetString("lblFirstName", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("MiddleName").HeaderText = _resources.GetString("lblMiddleName", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("LastName").HeaderText = _resources.GetString("lblLastName", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("CellPhone").HeaderText = _resources.GetString("lblCellPhone", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("Phone").HeaderText = _resources.GetString("lblPhone", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("Address").HeaderText = _resources.GetString("lblAddress", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("Email").HeaderText = _resources.GetString("lblEmail", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("ExternalId").HeaderText = _resources.GetString("lblExternalId", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("LoginId").HeaderText = _resources.GetString("lblLoginId", new CultureInfo(_culture));
        RadGrid1.MasterTableView.GetColumnSafe("IsSuper").HeaderText = _resources.GetString("IsSuper", new CultureInfo(_culture));
        
        RadGrid1.MasterTableView.EditFormSettings.CaptionFormatString = _resources.GetString("captionFormatString", new CultureInfo(_culture));
      
       // RadGrid1.ClientSettings.EnablePostBackOnRowClick = true;
        RadGrid1.ClientSettings.AllowColumnsReorder = true;
        RadGrid1.ClientSettings.ReorderColumnsOnClient = true;
        RadGrid1.ClientSettings.ColumnsReorderMethod = GridClientSettings.GridColumnsReorderMethod.Swap;
        RadGrid1.ClientSettings.AllowColumnHide = true;
        RadGrid1.ClientSettings.Resizing.AllowColumnResize = false;
        RadGrid1.ClientSettings.Resizing.AllowResizeToFit = true;
        RadGrid1.ClientSettings.Resizing.EnableRealTimeResize = true;
        RadGrid1.ClientSettings.Resizing.ResizeGridOnColumnResize = true;
        RadGrid1.ClientSettings.Resizing.AllowColumnResize = true;
        RadGrid1.ClientSettings.Resizing.ClipCellContentOnResize = true;
        RadGrid1.Culture = new CultureInfo(_culture);


        GridButtonColumn btndelete = (GridButtonColumn)RadGrid1.Columns.FindByUniqueName("btnDelete");
        btndelete.ConfirmText = _resources.GetString("confirmText", new CultureInfo(_culture));
        btndelete.ConfirmTitle = _resources.GetString("confirmTitle", new CultureInfo(_culture));

        switch (type)
        {
            case "New":
                UserListDialog.NavigateUrl = "UserForm.aspx";
                UserListDialog.VisibleOnPageLoad = true;
                break;
        }
      }

      private void SetTitle(string resx)
     {
          if (_resources == null || _culture == null) GetInfo();
        
          if (resx != null)
            lblTitle.Text = _resources.GetString(resx, new CultureInfo(_culture));
          
       }

      private void GetInfo()
      {
        _culture = App.CurrentCulture();
         _resources = App.GetAdminResources("UserManagement");  
      }

      #endregion

       
        
    }
}


Regards

1 Answer, 1 is accepted

Sort by
0
Accepted
Marin
Telerik team
answered on 07 Nov 2011, 12:13 PM
Hello Julieta,

 The code for adding the validators looks OK. You should check whether it is actually executed when you place the grid in insert mode. Also you can try to add the following setting to the markup of the grid which adds the specific commands that will trigger validation:

<ValidationSettings CommandsToValidate="PerformInsert,Update" />

If you fire RadConfirm from the server it executes a client-side script to show the pop-up so it does not return the selected result back on the server. You can only handle this on the client by providing a name of the callback function that will process the result as shown in this help topic:
http://www.telerik.com/help/aspnet-ajax/window-dialogs-confirm.html
I see in the code that you have provided that you already added a delete confirmation for the GridButtonColumn:
<telerik:GridButtonColumn UniqueName="btnDelete" ConfirmDialogType="RadWindow" ButtonType="ImageButton"
       CommandName="Delete" ConfirmDialogHeight="100px" ConfirmDialogWidth="300px" HeaderStyle-Width="3%" />

This is sufficient to show a confirmation pop-up on the client and it will only fire the delete command in case the result is positive. Having this in the markup makes redundant the need to fire RadConfirm from the server since the command will only be executed if the user has clicked OK. 
Regards,
Marin
the Telerik team
If you want to get updates on new releases, tips and tricks and sneak peeks at our product labs directly from the developers working on the RadControls for ASP.NET AJAX, subscribe to their blog feed now
Tags
Grid
Asked by
July
Top achievements
Rank 2
Answers by
Marin
Telerik team
Share this question
or