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

RadGrid entirely in CodeBehind

1 Answer 282 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Álvaro
Top achievements
Rank 1
Álvaro asked on 02 Jan 2019, 03:57 PM

I made a Grid entirely in CodeBehind, I used the personalizated Template to edit or insert new values.

 

RadGrid gridTemplate = new RadGrid();
DataSet dsTemplate = new DataSet();
dsTemplate = ReglasNotificacion.GetTemplates(Convert.ToInt32(dt.Rows[i]["rule_order"].ToString()));
 
gridTemplate.ID = "Grid_" + dt.Rows[i]["rule_order"].ToString();
gridTemplate.Attributes.Add("IDRegla", dt.Rows[i]["rule_order"].ToString());
gridTemplate.AllowPaging = true;
gridTemplate.PageSize = 10;
gridTemplate.AllowSorting = true;
gridTemplate.ShowStatusBar = true;
gridTemplate.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
gridTemplate.RenderMode = RenderMode.Auto;
gridTemplate.Skin = "Bootstrap";
gridTemplate.MasterTableView.AutoGenerateColumns = false;
gridTemplate.MasterTableView.DataKeyNames = new string[] { "Cod_Notification", "Cod_Site", "Cod_Template" };
gridTemplate.MasterTableView.CommandItemSettings.AddNewRecordText = "AƱadir nuevo registro.";
gridTemplate.MasterTableView.CommandItemSettings.ShowRefreshButton = false;
gridTemplate.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.Top;
gridTemplate.MasterTableView.EditMode = GridEditMode.EditForms;
gridTemplate.MasterTableView.EditFormSettings.EditFormType = GridEditFormType.Template;
gridTemplate.MasterTableView.EditFormSettings.FormTemplate = new MyEditFormTemplate();
gridTemplate.MasterTableView.AllowAutomaticUpdates = false;
gridTemplate.MasterTableView.AllowAutomaticDeletes = false;
gridTemplate.MasterTableView.AllowAutomaticInserts = false;
 
gridTemplate.ItemCommand += new GridCommandEventHandler(gridTemplate_ItemCommand);
 
GridEditCommandColumn edit = new GridEditCommandColumn();
edit.UniqueName = "EditCommandColumn";
gridTemplate.MasterTableView.Columns.Add(edit);
 
GridBoundColumn boundColumn;
 
boundColumn = new GridBoundColumn();
boundColumn.DataField = "Cod_Notification";
boundColumn.HeaderText = "Rule";
boundColumn.SortExpression = "Cod_Notification";
boundColumn.UniqueName = "Cod_Notification";
boundColumn.Visible = false;
gridTemplate.MasterTableView.Columns.Add(boundColumn);
 
boundColumn = new GridBoundColumn();
boundColumn.DataField = "Cod_Site";
boundColumn.HeaderText = "Site";
boundColumn.SortExpression = "Cod_Site";
boundColumn.UniqueName = "Cod_Site";
boundColumn.Visible = false;
gridTemplate.MasterTableView.Columns.Add(boundColumn);
 
boundColumn = new GridBoundColumn();
boundColumn.DataField = "Txt_Site";
boundColumn.HeaderText = "Site";
boundColumn.SortExpression = "Txt_Site";
boundColumn.UniqueName = "Txt_Site";
boundColumn.Visible = true;
boundColumn.ItemStyle.Width = new Unit(10, UnitType.Percentage);
gridTemplate.MasterTableView.Columns.Add(boundColumn);
 
boundColumn = new GridBoundColumn();
boundColumn.DataField = "Txt_Template";
boundColumn.HeaderText = "Template";
boundColumn.SortExpression = "Txt_Template";
boundColumn.UniqueName = "Txt_Template";
boundColumn.Visible = true;
boundColumn.ItemStyle.Width = new Unit(40, UnitType.Percentage);
gridTemplate.MasterTableView.Columns.Add(boundColumn);
 
boundColumn = new GridBoundColumn();
boundColumn.DataField = "Subject";
boundColumn.HeaderText = "Subject";
boundColumn.SortExpression = "Subject";
boundColumn.UniqueName = "Subject";
boundColumn.Visible = true;
boundColumn.ItemStyle.Width = new Unit(40, UnitType.Percentage);
gridTemplate.MasterTableView.Columns.Add(boundColumn);
 
boundColumn = new GridBoundColumn();
boundColumn.DataField = "Cod_Active";
boundColumn.HeaderText = "Active";
boundColumn.SortExpression = "Cod_Active";
boundColumn.UniqueName = "Cod_Active";
boundColumn.Visible = true;
boundColumn.ItemStyle.Width = new Unit(10, UnitType.Percentage);
gridTemplate.MasterTableView.Columns.Add(boundColumn);
 
GridButtonColumn gBtnColumn = new GridButtonColumn();
gBtnColumn.CommandName = "Delete";
gBtnColumn.Text = "Delete";
gBtnColumn.ButtonType = GridButtonColumnType.ImageButton;
gridTemplate.MasterTableView.Columns.Add(gBtnColumn);
 
gridTemplate.DataSource = dsTemplate;

 

I made the class to use to with the TemplateForm.

 

public class MyEditFormTemplate : IBindableTemplate
{
    public void InstantiateIn(Control container)
    {
        GridEditFormItem item = ((GridEditFormItem)(container.NamingContainer));
        //tb1.Text = item.ParentItem.OwnerTableView.DataKeyValues[((GridDataItem)(item.ParentItem)).ItemIndex]["ProviderName"].ToString();
 
        HtmlTable tableLine = new HtmlTable();
        tableLine.ID = "Table_Template";
        tableLine.Width = "100%";
        tableLine.Align = "center";
      
        HtmlTableRow rowTemplate = new HtmlTableRow();
 
        HtmlTableCell cellTemplate = new HtmlTableCell();
        HtmlTableCell cellTemplateSite = new HtmlTableCell();
        HtmlTableCell cellTemplateTemplate = new HtmlTableCell();
        HtmlTableCell cellTemplateSubject = new HtmlTableCell();
        HtmlTableCell cellTemplateActive = new HtmlTableCell();
        HtmlTableCell cellTemplateButton = new HtmlTableCell();
 
        DropDownList Site = new DropDownList();
        DropDownList Template = new DropDownList();
        TextBox Subject = new TextBox();
        RadButton Activo = new RadButton();
        ImageButton Aceptar = new ImageButton();
        ImageButton Cancelar = new ImageButton();
 
        DataTable dtSite = TENDERS_Administracion_DefinicionEnvioNotificaciones.getSites();
        DataRow drowSite = dtSite.NewRow();
        drowSite["COD_ITEM"] = "-1";
        drowSite["TXT_ITEM"] = "";
        dtSite.Rows.InsertAt(drowSite, 0);
 
        Site.DataSource = dtSite; //TENDERS_Administracion_DefinicionEnvioNotificaciones.getSites();
        Site.DataValueField = "COD_ITEM";
        Site.DataTextField = "TXT_ITEM";
        Site.Width = new Unit(70, UnitType.Percentage);
        Site.ID = "SiteRule";
 
        DataTable dtTemplate = TENDERS_Administracion_DefinicionEnvioNotificaciones.getTemplates();
        DataRow drowTemplate = dtTemplate.NewRow();
        drowTemplate["COD_ITEM"] = "-1";
        drowTemplate["TXT_ITEM"] = "";
        dtTemplate.Rows.InsertAt(drowTemplate, 0);
 
        Template.DataSource = dtTemplate; //TENDERS_Administracion_DefinicionEnvioNotificaciones.getTemplates();
        Template.DataValueField = "COD_ITEM";
        Template.DataTextField = "TXT_ITEM";
        Template.Width = new Unit(70, UnitType.Percentage);
        Template.ID = "TemplateRule";
 
        Subject.Width = new Unit(70, UnitType.Percentage);
        Subject.Style.Add("padding", "unset");
        Subject.Style.Add("height", "unset");
        Subject.Style.Add("border-color", "unset");
        Subject.Style.Add("border-radius", "unset");
        Subject.ID = "SubjectRule";
 
        Activo.ToggleType = ButtonToggleType.CheckBox;
        Activo.ButtonType = RadButtonType.ToggleButton;
        Activo.ToggleStates.Add("Activado");
        Activo.ToggleStates.Add("Desactivado");
        Activo.ID = "ActivoRule";
 
        Aceptar.ImageUrl = "~/MRA/img/Ico/guardar.png";
        Aceptar.CssClass = "GuardarRegla";
        Aceptar.ToolTip = "Guardar";
        Aceptar.CommandName = "Guardar";
        Aceptar.Style.Add("width", "11px");
        Aceptar.Style.Add("height", "11px");
        Aceptar.Style.Add("padding", "unset");
        Aceptar.Style.Add("border-radius", "unset");
        Aceptar.Style.Add("margin-right", "unset");
        Aceptar.Style.Add("border","unset !important");
 
        Cancelar.ImageUrl = "~/MRA/img/Ico/eliminar2.png";
        Cancelar.CssClass = "EliminarCondicion";
        Cancelar.ToolTip = "Cancelar";
        Cancelar.CommandName = "Cancelar";
        Cancelar.Style.Add("width", "11px");
        Cancelar.Style.Add("height", "11px");
        Cancelar.Style.Add("padding", "unset");
        Cancelar.Style.Add("border-radius", "unset");
        Cancelar.Style.Add("margin-right", "unset");
        Cancelar.Style.Add("margin-left", "4px");
        Cancelar.Style.Add("border", "unset !important");
 
        if (((Telerik.Web.UI.GridItem)container.NamingContainer).DataItem != null && (((Telerik.Web.UI.GridItem)container.NamingContainer).DataItem).ToString() != "Telerik.Web.UI.GridInsertionObject")
        {
            DataTable dtData = ((System.Data.DataRowView)((Telerik.Web.UI.GridItem)container.NamingContainer).DataItem).DataView.Table;
 
            Site.SelectedValue = dtData.Rows[0]["Cod_Site"].ToString();
            Template.SelectedValue = dtData.Rows[0]["Cod_Template"].ToString();
            Subject.Text = dtData.Rows[0]["Subject"].ToString();
            Activo.Checked = dtData.Rows[0]["COD_ACTIVE"].ToString() == "S" ? true : false;
        }
 
        cellTemplate.Style.Add("width", "2%");
        cellTemplateSite.Controls.Add(Site);
        cellTemplateSite.Style.Add("width", "10%");
        cellTemplateTemplate.Controls.Add(Template);
        cellTemplateTemplate.Style.Add("width", "40%");
        cellTemplateSubject.Controls.Add(Subject);
        cellTemplateSubject.Style.Add("width", "40%");
        cellTemplateActive.Controls.Add(Activo);
        cellTemplateActive.Style.Add("width", "10%");
        cellTemplateButton.Controls.Add(Aceptar);
        cellTemplateButton.Controls.Add(Cancelar);
 
        rowTemplate.Cells.Add(cellTemplate);
        rowTemplate.Cells.Add(cellTemplateSite);
        rowTemplate.Cells.Add(cellTemplateTemplate);
        rowTemplate.Cells.Add(cellTemplateSubject);
        rowTemplate.Cells.Add(cellTemplateActive);
        rowTemplate.Cells.Add(cellTemplateButton);
 
        tableLine.Rows.Add(rowTemplate);
 
        container.Controls.Add(tableLine);
    }
    public System.Collections.Specialized.IOrderedDictionary ExtractValues(System.Web.UI.Control container)
    {
        OrderedDictionary od = new OrderedDictionary();
 
        od.Add("IDRegla", ((RadGrid)container.Parent.Parent.Parent).Attributes["IDRegla"].ToString());
 
        od.Add("Cod_Notification", ((GridEditFormItem)(container)).ParentItem.OwnerTableView.DataKeyValues[((GridDataItem)(((GridEditFormItem)(container)).ParentItem)).ItemIndex]["Cod_Notification"].ToString());
        od.Add("Cod_Site", ((GridEditFormItem)(container)).ParentItem.OwnerTableView.DataKeyValues[((GridDataItem)(((GridEditFormItem)(container)).ParentItem)).ItemIndex]["Cod_Site"].ToString());
        od.Add("Cod_Template", ((GridEditFormItem)(container)).ParentItem.OwnerTableView.DataKeyValues[((GridDataItem)(((GridEditFormItem)(container)).ParentItem)).ItemIndex]["Cod_Template"].ToString());
 
        od.Add("Site", ((DropDownList)(((GridEditFormItem)(container)).FindControl("SiteRule"))).SelectedValue);
        od.Add("Template", ((DropDownList)(((GridEditFormItem)(container)).FindControl("TemplateRule"))).SelectedValue);
        od.Add("Subject", ((TextBox)(((GridEditFormItem)(container)).FindControl("SubjectRule"))).Text);
        od.Add("Active", ((RadButton)(((GridEditFormItem)(container)).FindControl("ActivoRule"))).Checked == true ? 'S' : 'N');
        return od;
    }
 
}
 

 

But I have some problems.

- The form template doesn't disappear when used a imagebutton.

- When used the imagebutton to save data, I can't read ExtractValues for my form template class, because the ItemCommand doesn't use MyEditFormTemplate class.

 

protected void gridTemplate_ItemCommand(object sender, GridCommandEventArgs e)
    {
        string command = e.CommandName;
 
        if (command == "Cancelar")
        {
            e.Canceled = true;
        }
        else if (command == "Guardar")
        {
            e.Canceled = true;
            GridDataItem grid = ((GridDataItem )(e.Item));
            Hashtable table = new Hashtable();
            grid.ExtractValues(table);
        }
        //e.KeepInEditMode = true;
        //((RadGrid)e.Item.Parent.Parent.Parent).DataBind();
        ((RadGrid)e.Item.Parent.Parent.Parent).Rebind();
    }

 

Any Idea?

Thank you very much

 

 

1 Answer, 1 is accepted

Sort by
0
Accepted
Attila Antal
Telerik team
answered on 04 Jan 2019, 03:46 PM
Hi Ɓlvaro,

In order to close the Edit form, RadGrid must receive the commands Update or Cancel, and since the commands Guardar and Cancelar do not instruct the grid for further action, nothing happens. For the same reason, the EditFormItem is not available in the ItemCommand event.

To fix that, you can either use the built-in commands or catch the custom commands in the ItemCommand event and tell RadGrid what to do next. To see a list if built-in commands check out the How to Fire Command Events article. 

Example code to catch the custom command in the ItemCommand event, then Fire the respective built-in commands.

private void GridTemplate_ItemCommand(object sender, GridCommandEventArgs e)
{
    if(e.CommandName == "Guardar")
    {
        (e.Item as GridDataItem).FireCommandEvent("Update", "");
    }
}

Although, I believe it would be easier to fire the built-in command, and cancel the event if something does not go as planned. You can make the buttons do that as follows:

Cancelar.CommandName = "Cancel";
Aceptar.CommandName = "Update";

In the ItemCommand event handler you can then do something like:

private void GridTemplate_ItemCommand(object sender, GridCommandEventArgs e)
{
    if(e.CommandName == RadGrid.UpdateCommandName || e.CommandName == RadGrid.UpdateEditedCommandName)
    {
        // if condition not met, cancel the event
        if (false)
        {
            e.Canceled = true;
            return;
        }
 
        // proceed further
    }
}

Since Templates can contain anything the developer inserts, Extracting values for them needs to be done manually by following the approach described in the Accessing Controls in Template Column and Updating Values Using UserControl and FormTemplate articles.

Kind regards,
Attila Antal
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
Grid
Asked by
Álvaro
Top achievements
Rank 1
Answers by
Attila Antal
Telerik team
Share this question
or