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

Class to create Radgrid dynamically

2 Answers 39 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Brad
Top achievements
Rank 1
Brad asked on 23 Sep 2013, 02:26 PM
I am trying to create a class that will allow me to create a radgrid dynamically. Then i have it load on page_load or page_init and i get the same problem. It creates the grid no problem, but when i click on delete, it deletes one record, and then if i click on delete again, it just refreshes the page and nothing happens. Also if i click on insert, it will insert one record and that's it, and then if i try to insert another record, the last record inserted gets deleted.

Class File (invoicer.cs)
public class invoicer
{
    public invoicer()
    {
        //
        // TODO: Add constructor logic here
        //
 
        string currentSession = HttpContext.Current.Session.SessionID;
        DataTable dt = GetTable();
        HttpContext.Current.Session.Add(currentSession, dt);
         
    }
 
    public class MyTemplate : ITemplate
    {
        private string colname;
        protected Label lControl;
        public MyTemplate(string cName)
        {
            colname = cName;
        }
        public void InstantiateIn(System.Web.UI.Control container)
        {
            lControl = new Label();
            lControl.ID = "Label-DurationType";
            lControl.DataBinding += new EventHandler(lControl_DataBinding);
            container.Controls.Add(lControl);
        }
 
        public void lControl_DataBinding(object sender, EventArgs e)
        {
            Label l = (Label)sender;
            GridDataItem container = (GridDataItem)l.NamingContainer;
            l.Text = ((DataRowView)container.DataItem)[colname].ToString() + "<br />";
        }
    }
 
 
    public class MyEditTemplate : IBindableTemplate
    {
        public void InstantiateIn(Control container)
        {
            GridDataItem item = ((GridDataItem)(container.NamingContainer));
            DropDownList drop = new DropDownList();
            drop.ID = "DurationType-DDL";
            drop.DataSource = (DataTable)GetTableForDropDown();
            drop.DataTextField = "DurationType";
            drop.DataValueField = "DurationType";
 
            container.Controls.Add(drop);
        }
        public System.Collections.Specialized.IOrderedDictionary ExtractValues(System.Web.UI.Control container)
        {
            OrderedDictionary od = new OrderedDictionary();
            od.Add("DurationType", ((DropDownList)(((GridDataItem)(container)).FindControl("DurationType-DDL"))).DataValueField);
            return od;
        }
    }
 
    protected void grid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
        {
            GridEditFormItem editItem = (GridEditFormItem)e.Item;
            DropDownList ddl = (DropDownList)editItem.FindControl("DurationType-DDL");
            ddl.DataSource = (DataTable)GetTableForDropDown();
            ddl.DataTextField = "DurationType";
            ddl.DataValueField = "DurationType";
            ddl.SelectedIndex = editItem.ItemIndex;
        }
    }
 
 
 
    public void DefineGridStructure(int i, PlaceHolder ph)
    {
        RadGrid grid = new RadGrid();
        grid.ID = "RadGrid" + i.ToString();
        grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource);
        grid.AutoGenerateEditColumn = true;
        grid.AutoGenerateDeleteColumn = true;
        grid.AllowAutomaticInserts = false;
        grid.Width = Unit.Percentage(100);
        grid.PageSize = 15;
        grid.AllowPaging = true;
        grid.AllowFilteringByColumn = true;
        grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
        grid.AutoGenerateColumns = false;
        grid.MasterTableView.Width = Unit.Percentage(100);
        grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.TopAndBottom;
        grid.AllowAutomaticDeletes = false;
        grid.AllowAutomaticUpdates = false;
        grid.ItemDataBound += new GridItemEventHandler(grid_ItemDataBound);
        grid.InsertCommand += grid_InsertCommand;
        grid.DeleteCommand += grid_DeleteCommand;
        grid.UpdateCommand += grid_UpdateCommand;
        grid.MasterTableView.DataKeyNames = new string[] { "RowNumber" };
        GridBoundColumn boundColumn = new GridBoundColumn();
        boundColumn.DataField = "RowNumber";
        boundColumn.HeaderText = "RowNumber";
        boundColumn.ReadOnly = true;
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Size";
        boundColumn.HeaderText = "Size";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Description";
        boundColumn.HeaderText = "Description";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Quantity";
        boundColumn.HeaderText = "Quantity";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Unit";
        boundColumn.HeaderText = "Unit";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Duration";
        boundColumn.HeaderText = "Duration";
        grid.MasterTableView.Columns.Add(boundColumn);
 
        GridTemplateColumn objGridTemplateColumn = new GridTemplateColumn();
        objGridTemplateColumn.HeaderText = "DurationType";
        objGridTemplateColumn.DataField = "DurationType";
        objGridTemplateColumn.ItemTemplate = new MyTemplate("DurationType");
        objGridTemplateColumn.EditItemTemplate = new MyEditTemplate();
        grid.MasterTableView.Columns.Add(objGridTemplateColumn);
 
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Amount";
        boundColumn.HeaderText = "Amount";
        grid.MasterTableView.Columns.Add(boundColumn);
        grid.MasterTableView.EditMode = GridEditMode.InPlace;
        ph.Controls.Add(grid);
    }
 
 
    public void grid_UpdateCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editItem = e.Item as GridEditableItem;
        Hashtable newValues = new Hashtable();
        newValues["RowNumber"] = (editItem["RowNumber"].Controls[0] as TextBox).Text;
        newValues["Size"] = (editItem["Size"].Controls[0] as TextBox).Text;
        newValues["Description"] = (editItem["Description"].Controls[0] as TextBox).Text;
        newValues["Quantity"] = (editItem["Quantity"].Controls[0] as TextBox).Text;
        newValues["Unit"] = (editItem["Unit"].Controls[0] as TextBox).Text;
        newValues["Duration"] = (editItem["Duration"].Controls[0] as TextBox).Text;
        newValues["DurationType"] = (editItem.FindControl("DurationType-DDL") as DropDownList).SelectedValue;
        newValues["Amount"] = (editItem["Amount"].Controls[0] as TextBox).Text;
        DataTable dtCurrentTable = (DataTable)HttpContext.Current.Session[HttpContext.Current.Session.SessionID];
        foreach (DictionaryEntry entry in newValues)
        {
            dtCurrentTable.Rows[e.Item.ItemIndex][entry.Key.ToString()] = entry.Value;
        }
    }
 
 
    public void grid_DeleteCommand(object sender, GridCommandEventArgs e)
    {
        GridDataItem item = e.Item as GridDataItem;
        DataTable dt = (DataTable)HttpContext.Current.Session[HttpContext.Current.Session.SessionID];
        dt.Rows.Remove(dt.Rows[item.ItemIndex]);
        ResetRowID(dt);
    }
 
    public void grid_InsertCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;
        GridEditManager editMan = editedItem.EditManager;
        //Set new values
        Hashtable newValues = new Hashtable();
        //The GridTableView will fill the values from all editable columns in the hash
 
        DataTable dtCurrentTable = (DataTable)HttpContext.Current.Session[HttpContext.Current.Session.SessionID];
        DataRow dr = null;
        int count = dtCurrentTable.Rows.Count;
        count++;
        dr = dtCurrentTable.NewRow();
        dr["RowNumber"] = count;
        newValues["RowNumber"] = count;
        newValues["Size"] = (editedItem["Size"].Controls[0] as TextBox).Text;
        newValues["Description"] = (editedItem["Description"].Controls[0] as TextBox).Text;
        newValues["Quantity"] = (editedItem["Quantity"].Controls[0] as TextBox).Text;
        newValues["Unit"] = (editedItem["Unit"].Controls[0] as TextBox).Text;
        newValues["Duration"] = (editedItem["Duration"].Controls[0] as TextBox).Text;
        newValues["DurationType"] = (editedItem.FindControl("DurationType-DDL") as DropDownList).SelectedValue;
        newValues["Amount"] = (editedItem["Amount"].Controls[0] as TextBox).Text;
        foreach (DictionaryEntry entry in newValues)
        {
            dr[entry.Key.ToString()] = entry.Value;
        }
        dtCurrentTable.Rows.Add(dr);
    }
 
    void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        DataTable current = (DataTable)HttpContext.Current.Session[HttpContext.Current.Session.SessionID];
        RadGrid grid = (RadGrid)sender;
        grid.DataSource = current;
    }
 
 
    static DataTable GetTable()
    {
        //
        // Here we create a DataTable with a few columns.
        //
        // Create Datatable to store all colums
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Size", typeof(string)));
        dt.Columns.Add(new DataColumn("Description", typeof(string)));
        dt.Columns.Add(new DataColumn("Quantity", typeof(string)));
        dt.Columns.Add(new DataColumn("Unit", typeof(string)));
        dt.Columns.Add(new DataColumn("Duration", typeof(string)));
        dt.Columns.Add(new DataColumn("DurationType", typeof(string)));
        dt.Columns.Add(new DataColumn("Amount", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 2;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 3;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 4;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 5;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
        return dt;
    }
 
    static DataTable GetTableForDropDown()
    {
        //
        // Here we create a DataTable with a few columns.
        //
        // Create Datatable to store all colums
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("DurationType", typeof(string)));
 
        dr = dt.NewRow();
        dr["DurationType"] = "Hours";
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["DurationType"] = "Days";
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["DurationType"] = "Weeks";
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["DurationType"] = "Months";
        dt.Rows.Add(dr);
        return dt;
    }
 
    private void ResetRowID(DataTable dt)
    {
        int rowNumber = 1;
 
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                row[0] = rowNumber;
                rowNumber++;
            }
        }
    }
 
}




I try to add it to the default.aspx,cs page

public partial class Default : System.Web.UI.Page
{
 
    protected void Page_Init(object sender, System.EventArgs e)
    {
        invoicer inv = new invoicer();
        inv.DefineGridStructure(1, PlaceHolder1);
    }
 
 
    protected void Page_Load(object sender, EventArgs e)
    {
                
    }
 
 
}


I'm sure i'm doing something wrong, any help is very much appreciated.

2 Answers, 1 is accepted

Sort by
0
Brad
Top achievements
Rank 1
answered on 24 Sep 2013, 12:48 PM
I have somewhat created a class to create radgrids dynamically, but i run into the following issue.

I am trying to get it to where i can create a radgrid on demand, so it first loads up one radgrid, and then on button click i can create as many as needed. But the issue is, when i create more than one, it seems to display them fine, meaning the top one would be the current and below would be the previous ones. But  i want to be able to click on any of the grids and be able to edit the one that is clicked on. But what is happening now, is that no matter which one i click on, it displays only the current one in its own page, and lets me edit it and all, but as soon as i create another grid, all changes get deleted.

Any help is very much appreciated.

invoicer.cs
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
 
/// <summary>
/// Summary description for invoicer
/// </summary>
public class invoicer
{
    public invoicer()
    {
        //
        // TODO: Add constructor logic here
        //
  
    }
 
 
    public class MyTemplate : ITemplate
    {
        private string colname;
        protected Label lControl;
        public MyTemplate(string cName)
        {
            colname = cName;
        }
        public void InstantiateIn(System.Web.UI.Control container)
        {
            lControl = new Label();
            lControl.ID = "Label-DurationType";
            lControl.DataBinding += new EventHandler(lControl_DataBinding);
            container.Controls.Add(lControl);
        }
 
        public void lControl_DataBinding(object sender, EventArgs e)
        {
            Label l = (Label)sender;
            GridDataItem container = (GridDataItem)l.NamingContainer;
            l.Text = ((DataRowView)container.DataItem)[colname].ToString() + "<br />";
        }
    }
 
    public class MyEditTemplate : IBindableTemplate
    {
        public void InstantiateIn(Control container)
        {
            GridDataItem item = ((GridDataItem)(container.NamingContainer));
            DropDownList drop = new DropDownList();
            drop.ID = "DurationType-DDL";
            drop.DataSource = (DataTable)GetTableForDropDown();
            drop.DataTextField = "DurationType";
            drop.DataValueField = "DurationType";
            container.Controls.Add(drop);
        }
 
        public System.Collections.Specialized.IOrderedDictionary ExtractValues(System.Web.UI.Control container)
        {
            OrderedDictionary od = new OrderedDictionary();
            od.Add("DurationType", ((DropDownList)(((GridDataItem)(container)).FindControl("DurationType-DDL"))).DataValueField);
            return od;
        }
    }
 
    void grid_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
    {
        DataTable current = (DataTable)HttpContext.Current.Session[GetSession()];
        RadGrid grid = (RadGrid)sender;
        grid.DataSource = current;
    }
 
 
 
    protected void grid_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
    {
        if (e.Item is GridEditFormItem && e.Item.IsInEditMode)
        {
            GridEditFormItem editItem = (GridEditFormItem)e.Item;
            DropDownList ddl = (DropDownList)editItem.FindControl("dropdownlist1");
            ddl.DataSource = (DataTable)GetTableForDropDown();
            ddl.DataTextField = "DurationType";
            ddl.DataValueField = "DurationType";
            ddl.SelectedIndex = editItem.ItemIndex;
            ddl.SelectedValue = DataBinder.Eval(editItem.DataItem, "DurationType").ToString(); // To get the selected value         
        }
    }
 
 
    public void DefineGridStructure(int i, PlaceHolder ph)
    {
 
 
 
        RadGrid grid = new RadGrid();
        grid.ID = "RadGrid" + i.ToString();
        grid.NeedDataSource += new GridNeedDataSourceEventHandler(grid_NeedDataSource);
        grid.AutoGenerateEditColumn = true;
        grid.AutoGenerateDeleteColumn = true;
        grid.AllowAutomaticInserts = false;
        grid.Width = Unit.Percentage(100);
        grid.PageSize = 15;
        grid.AllowPaging = true;
        grid.AllowFilteringByColumn = false;
        grid.PagerStyle.Mode = GridPagerMode.NextPrevAndNumeric;
        grid.AutoGenerateColumns = false;
        grid.MasterTableView.Width = Unit.Percentage(100);
        grid.MasterTableView.CommandItemDisplay = GridCommandItemDisplay.TopAndBottom;
        grid.AllowAutomaticDeletes = false;
        grid.AllowAutomaticUpdates = false;
        grid.ItemDataBound += new GridItemEventHandler(grid_ItemDataBound);
        grid.InsertCommand += grid_InsertCommand;
        grid.DeleteCommand += grid_DeleteCommand;
        grid.UpdateCommand += grid_UpdateCommand;
        grid.MasterTableView.DataKeyNames = new string[] { "RowNumber" };
        GridBoundColumn boundColumn = new GridBoundColumn();
        boundColumn.DataField = "RowNumber";
        boundColumn.HeaderText = "RowNumber";
        boundColumn.ReadOnly = true;
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Size";
        boundColumn.HeaderText = "Size";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Description";
        boundColumn.HeaderText = "Description";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Quantity";
        boundColumn.HeaderText = "Quantity";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Unit";
        boundColumn.HeaderText = "Unit";
        grid.MasterTableView.Columns.Add(boundColumn);
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Duration";
        boundColumn.HeaderText = "Duration";
        grid.MasterTableView.Columns.Add(boundColumn);
 
        GridTemplateColumn objGridTemplateColumn = new GridTemplateColumn();
        objGridTemplateColumn.HeaderText = "DurationType";
        objGridTemplateColumn.DataField = "DurationType";
        objGridTemplateColumn.ItemTemplate = new MyTemplate("DurationType");
        objGridTemplateColumn.EditItemTemplate = new MyEditTemplate();
        grid.MasterTableView.Columns.Add(objGridTemplateColumn);
 
        boundColumn = new GridBoundColumn();
        boundColumn.DataField = "Amount";
        boundColumn.HeaderText = "Amount";
        grid.MasterTableView.Columns.Add(boundColumn);
        grid.MasterTableView.EditMode = GridEditMode.InPlace;
        ph.Controls.Add(grid);
    }
 
 
    public void grid_UpdateCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editItem = e.Item as GridEditableItem;
        Hashtable newValues = new Hashtable();
        newValues["RowNumber"] = (editItem["RowNumber"].Controls[0] as TextBox).Text;
        newValues["Size"] = (editItem["Size"].Controls[0] as TextBox).Text;
        newValues["Description"] = (editItem["Description"].Controls[0] as TextBox).Text;
        newValues["Quantity"] = (editItem["Quantity"].Controls[0] as TextBox).Text;
        newValues["Unit"] = (editItem["Unit"].Controls[0] as TextBox).Text;
        newValues["Duration"] = (editItem["Duration"].Controls[0] as TextBox).Text;
        newValues["DurationType"] = (editItem.FindControl("DurationType-DDL") as DropDownList).SelectedValue;
        newValues["Amount"] = (editItem["Amount"].Controls[0] as TextBox).Text;
        DataTable dtCurrentTable = (DataTable)HttpContext.Current.Session[GetSession()];
 
        foreach (DictionaryEntry entry in newValues)
        {
            dtCurrentTable.Rows[e.Item.ItemIndex][entry.Key.ToString()] = entry.Value;
        }
        SaveTable();
 
    }
 
    public void grid_DeleteCommand(object sender, GridCommandEventArgs e)
    {
        GridDataItem item = e.Item as GridDataItem;
        DataTable dt = (DataTable)HttpContext.Current.Session[GetSession()];
        dt.Rows.Remove(dt.Rows[item.ItemIndex]);
        ResetRowID(dt);
        SaveTable();
    }
 
    public void grid_InsertCommand(object sender, GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;
        GridEditManager editMan = editedItem.EditManager;
        //Set new values
        Hashtable newValues = new Hashtable();
        //The GridTableView will fill the values from all editable columns in the hash
 
        DataTable dtCurrentTable = (DataTable)HttpContext.Current.Session[GetSession()];
        DataRow dr = null;
        int count = dtCurrentTable.Rows.Count;
        count++;
        dr = dtCurrentTable.NewRow();
        dr["RowNumber"] = count;
        newValues["RowNumber"] = count;
        newValues["Size"] = (editedItem["Size"].Controls[0] as TextBox).Text;
        newValues["Description"] = (editedItem["Description"].Controls[0] as TextBox).Text;
        newValues["Quantity"] = (editedItem["Quantity"].Controls[0] as TextBox).Text;
        newValues["Unit"] = (editedItem["Unit"].Controls[0] as TextBox).Text;
        newValues["Duration"] = (editedItem["Duration"].Controls[0] as TextBox).Text;
        newValues["DurationType"] = (editedItem.FindControl("DurationType-DDL") as DropDownList).SelectedValue;
        newValues["Amount"] = (editedItem["Amount"].Controls[0] as TextBox).Text;
        foreach (DictionaryEntry entry in newValues)
        {
            dr[entry.Key.ToString()] = entry.Value;
        }
        dtCurrentTable.Rows.Add(dr);
        SaveTable();
    }
 
 
 
    public string GetSession()
    {
        string SID = HttpContext.Current.Session["Tables"].ToString();
        return SID;
    }
 
    public void SaveTable()
    {
        DataTable dtCurrentTable = (DataTable)HttpContext.Current.Session[GetSession()];
        HttpContext.Current.Session.Add(GetSession(), dtCurrentTable);
    }
 
   public DataTable GetTable()
    {
        //
        // Here we create a DataTable with a few columns.
        //
        // Create Datatable to store all colums
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("RowNumber", typeof(string)));
        dt.Columns.Add(new DataColumn("Size", typeof(string)));
        dt.Columns.Add(new DataColumn("Description", typeof(string)));
        dt.Columns.Add(new DataColumn("Quantity", typeof(string)));
        dt.Columns.Add(new DataColumn("Unit", typeof(string)));
        dt.Columns.Add(new DataColumn("Duration", typeof(string)));
        dt.Columns.Add(new DataColumn("DurationType", typeof(string)));
        dt.Columns.Add(new DataColumn("Amount", typeof(string)));
        dr = dt.NewRow();
        dr["RowNumber"] = 1;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 2;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 3;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 4;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["RowNumber"] = 5;
        dr["Size"] = string.Empty;
        dr["Description"] = string.Empty;
        dr["Quantity"] = string.Empty;
        dr["Unit"] = string.Empty;
        dr["Duration"] = string.Empty;
        dr["DurationType"] = string.Empty;
        dr["Amount"] = string.Empty;
        dt.Rows.Add(dr);
        return dt;
    }
 
 
    static DataTable GetTableForDropDown()
    {
        //
        // Here we create a DataTable with a few columns.
        //
        // Create Datatable to store all colums
        DataTable dt = new DataTable();
        DataRow dr = null;
        dt.Columns.Add(new DataColumn("DurationType", typeof(string)));
 
        dr = dt.NewRow();
        dr["DurationType"] = "Hours";
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["DurationType"] = "Days";
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["DurationType"] = "Weeks";
        dt.Rows.Add(dr);
 
        dr = dt.NewRow();
        dr["DurationType"] = "Months";
        dt.Rows.Add(dr);
        return dt;
    }
 
    private void ResetRowID(DataTable dt)
    {
        int rowNumber = 1;
 
        if (dt.Rows.Count > 0)
        {
            foreach (DataRow row in dt.Rows)
            {
                row[0] = rowNumber;
                rowNumber++;
            }
        }
    }
 
 
}


Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class Default : System.Web.UI.Page
{
 
    invoicer inv = new invoicer();
 
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Tables"] == null)
        {
         
            Session.Add("Tables", 1);
         
            DataTable dt = inv.GetTable();
         
            Session.Add(Session["Tables"].ToString(), dt);
         
        }
         
        Label lbl = new Label();
        lbl.ID = "LABELS-" + Session["Tables"].ToString();
        lbl.Text = "This is Table in PH1 " + Session["Tables"].ToString();
        PlaceHolder1.Controls.Add(lbl);
        inv.DefineGridStructure((int)Session["Tables"], PlaceHolder1);
         
    }
 
 
 
    protected void Button1_Click(object sender, EventArgs e)
    {
         
        int next = (int)Session["Tables"];
        next = next + 1;
         
        Session.Add("Tables", next);
         
        DataTable dt = inv.GetTable();
         
        Session.Add(Session["Tables"].ToString(), dt);
       
        
 
        for (int i = 1; i <= (int)Session["Tables"]; i++)
        {
            Label lbl = new Label();
            lbl.ID = "LABELS-" + i.ToString();
            lbl.Text = "This is Table in PH2 " + i.ToString();
            PlaceHolder2.Controls.Add(lbl);
            inv.DefineGridStructure(i, PlaceHolder2);
        }
    }
 
  
}

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" %>
  
<%@ Register Assembly="Telerik.Web.UI" Namespace="Telerik.Web.UI" TagPrefix="telerik" %>
  
<!DOCTYPE html>
  
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <telerik:RadScriptManager ID="RadScriptManager1" runat="server"></telerik:RadScriptManager>
    <div>
          
        <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        <br /><br /><br />
        <asp:PlaceHolder ID="PlaceHolder2" runat="server"></asp:PlaceHolder>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>
0
Marin
Telerik team
answered on 26 Sep 2013, 08:22 AM
Hello,

 The nature of the ASP.NET framework requires all server-side controls to be added in the OnInit page event when they are created dynamically - this will ensure correct property persistence in ViewState and functioning of all features as expected.
That's why dynamically adding grids (or other server-side controls) on button click is not supported and can lead to further complications.
When you create the grid dynamically from scratch it is recommended to do this in the Page_Init as shown in this help topic:
http://www.telerik.com/help/aspnet-ajax/grid-programmatic-creation.html#Section22
If you follow this approach strictly all operations in the control including insert and delete should be working as expected.

Regards,
Marin
Telerik
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 the blog feed now.
Tags
Grid
Asked by
Brad
Top achievements
Rank 1
Answers by
Brad
Top achievements
Rank 1
Marin
Telerik team
Share this question
or