Dynamically created textbox in RadGrid

18 posts, 0 answers
  1. Clifton Brown
    Clifton Brown avatar
    8 posts
    Member since:
    Jun 2008

    Posted 04 Mar 2009 Link to this post

    Hello,
    I'm have a RadGrid with 2 template columns. During ItemDataBound I'm dynamically creating a textbox and adding it to the Grid like this:

    GridDataItem gdi = (GridDataItem)e.item

    TextBox tb = new TextBox();
    tb.ID = tbID;
    tb.EnabeViewState = true;
    gdi["column name"].controls.add(tb);

    "Colum name" is a template column in the grid

    I have another template column with a button in it that is created at design time. When I click that button I want to be able to find the dynamically created text box in the same row of the grid and read it's value.
    How do I accomplish this?

    Thanks in advance
  2. Daniel
    Admin
    Daniel avatar
    4945 posts

    Posted 04 Mar 2009 Link to this post

    Hello Clifton,

    You can find a sample snippet below:
    <telerik:RadGrid ID="RadGrid1" runat="server" Width="580px" Skin="Forest" OnItemCreated="RadGrid1_ItemCreated"
        <MasterTableView> 
            <Columns> 
                <telerik:GridTemplateColumn HeaderText="1" UniqueName="Column1"
                    <ItemTemplate> 
                        <asp:Button ID="Button1" Text="Click here" runat="server" OnClick="Button1_Click" /> 
                    </ItemTemplate> 
                </telerik:GridTemplateColumn> 
                <telerik:GridTemplateColumn HeaderText="2" UniqueName="Column2"
                    <ItemTemplate> 
                        &nbsp; 
                    </ItemTemplate> 
                </telerik:GridTemplateColumn> 
            </Columns> 
        </MasterTableView> 
    </telerik:RadGrid> 


    protected void Page_Load(object sender, EventArgs e) 
        RadGrid1.DataSource = new int[] { 0, 1, 2, 3, 4 }; 

    protected void Button1_Click(object sender, EventArgs e) 
        GridDataItem item = (sender as Button).Parent.Parent as GridDataItem; 
        Button btn2 = item.FindControl("Button2"as Button; 
        btn2.BackColor = System.Drawing.Color.Blue; 
     
    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e) 
        if (e.Item is GridDataItem) 
        { 
            GridDataItem item = e.Item as GridDataItem; 
            Button btn2 = new Button(); 
            btn2.Text = "Another button"
            btn2.ID = "Button2"
            item["Column2"].Controls.Add(btn2); 
        } 

    Hope this helps.

    Best regards,
    Daniel
    the Telerik team

    Instantly find answers to your questions on the new Telerik Support Portal.
    Check out the tips for optimizing your support resource searches.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Clifton Brown
    Clifton Brown avatar
    8 posts
    Member since:
    Jun 2008

    Posted 04 Mar 2009 Link to this post

    You guys are awesome! that did it. I was creating my controls in ItemDataBound instead of ItemCreated.

    Thanks!
  5. Raj
    Raj avatar
    2 posts
    Member since:
    Sep 2011

    Posted 15 Sep 2011 Link to this post

    Hey can anyone help me
    I want to add a control in a cell in radgrid something like we do in gridview eg:

    GridView.Rows[i].Cells[j].Controls.Add(txt);
    Its urgent any help will be highly thankfull.

  6. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 15 Sep 2011 Link to this post

    Hello Raj,

    The following documentation describes how to access cells and rows.
    Accessing Cells and Rows.

    Thanks,
    Shinu.
  7. Raj
    Raj avatar
    2 posts
    Member since:
    Sep 2011

    Posted 15 Sep 2011 Link to this post

    Thanks Shinu.

    Bhut i didnt see any code to add controls in a cell in the link you have provided.
    can you help me on this.I want to add a control in runtime in a specific cell in radgrid.
  8. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 15 Sep 2011 Link to this post

    Hello Raj,

    Try the following code snippet to achieve your scenario.
    C#:
    protected void RadGrid2_ItemCreated(object sender, GridItemEventArgs e)
       {
           if (e.Item is GridDataItem)
           {
               GridDataItem item=(GridDataItem)e.Item;
               Label l1 = new Label();
               l1.Text = "Hi";
               e.Item.Cells[1].Controls.Add(l1); 
           }
       }

    Thanks,
    Shinu.
  9. Nubia Stefania
    Nubia Stefania avatar
    2 posts
    Member since:
    Nov 2012

    Posted 28 Nov 2012 Link to this post

    Hello,

    I'm trying to access the values ​​to the control that tells me agrege but not instantiated, any tip I can give for this

    Thanks
  10. Daniel
    Admin
    Daniel avatar
    4945 posts

    Posted 03 Dec 2012 Link to this post

    Hello Nubia Stefania,

    I'm not sure that I fully understand the problem. Could you please provide some more details?

    Kind regards,
    Daniel
    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.
  11. JJ
    JJ avatar
    21 posts
    Member since:
    Jul 2014

    Posted 21 Jul 2014 Link to this post

    This is working fine:

    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e) 
    {    
     if (e.Item is GridDataItem)  
       {         
    GridDataItem item = e.Item as GridDataItem;        
     Button btn2 = new Button();    
         btn2.Text = "Another button";  
           btn2.ID = "Button2";     
        item["Column2"].Controls.Add(btn2);   
      } 



    I can successfully build different columns and its different controls in each row.

    At save my TabelCell controls is empty:

    TableCell cell = dataItem["ColumnUniqueName"]; //working
    TextBox textBox = dataItem.FindControl("TextBoxID") as TextBox; //not working

    why?

  12. Princy
    Princy avatar
    17421 posts
    Member since:
    Mar 2007

    Posted 22 Jul 2014 in reply to JJ Link to this post

    Hi JJ,

    I'm not clear about your requirement, I guess you are dynamically creating a TextBox in view mode and trying to access it value on a button which is outside grid. Please take a look at the following code snippet.

    C#:
    //Create controls in ItemDataBound and ItemCreated events
    protected void rgrdSample_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem dataItem = (GridDataItem)e.Item;
            TextBox txtsample = new TextBox();
            txtsample.ID = "txtSample";
            dataItem["Name"].Controls.Add(txtsample);
        }
    }
    protected void rgrdSample_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem dataItem = (GridDataItem)e.Item;
            TextBox txtsample = new TextBox();
            txtsample.ID = "txtSample";
            dataItem["Name"].Controls.Add(txtsample);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        foreach (GridDataItem dataItem in rgrdSample.Items)
        {
            TableCell cell = dataItem["Name"]; //Gives the Column Value
            TextBox textBox = dataItem.FindControl("txtSample") as TextBox; //Get the Text entered in TextBox
        }
    }

    Thanks,
    Princy
  13. JJ
    JJ avatar
    21 posts
    Member since:
    Jul 2014

    Posted 22 Jul 2014 Link to this post

    Yes that is the code I am using, but with AjaxSetting AjaxUpdatedControl in asp.net and I build my columns of the RadGrid with deep copy when the client click on a load button... then I build the different controls in _ItemCreated event in each column I created... It works fine...


    c#:

    ...
     for (int tel = 0; tel < tableView.Columns.Count; tel++)
    {
    if (tableView.Columns[tel] != null && tableView.Columns[tel].GetType() == typeof(GridTemplateColumn))

    GridTemplateColumn oColumn = (GridTemplateColumn)tableView.Columns[tel];
    .... 
    DeepcopyColumns_[no] = (GridTemplateColumn)oColumn.Clone();
    ... //do some changes to the column like HeaderText // I also tried a GridBoundColumn, it made no difference
    tableView.Columns.AddAt(pos, DeepcopyColumns[number]);

    This part is not working at save, the Cell-table controls property is empty and/or it do not find the control by its Unique ID or ID:
    TextBox textBox = dataItem.FindControl("txtSample") as TextBox; //Get the Text entered in TextBox

  14. JJ
    JJ avatar
    21 posts
    Member since:
    Jul 2014

    Posted 22 Jul 2014 Link to this post

    Solution:

    1. I had to create a aspx user control and move the RadGrid in that control...
    2. On button load add the user control in code-behind in a ajax-panel or rad-pane...
    userControl = (File)LoadControl(filePath + psFileName);
    Pane.Controls.Add(userControl);

    3. Had to use Session variables to store and use ID's accross master page and user control...

    4. Create the Columns and load of RadGrid Data inside the Init...
    protected override void OnInit(EventArgs e)
    {
                int ID = (int)Session["sessionName"];
                CreateColumnsAndLoadData(ID);
    }

    5. Still create controls and Load/Bind Control Values in ItemCreate event... 
    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
    6. NB!<Create Control ID's with GUID's for validation expressions controls to work... use the control preRender Event>
    protected void Unnamed_PreRender(object sender, EventArgs e)
           {
               if (sender != null)
               {
                   var parent = ((RegularExpressionValidator)sender).Parent;
                   if (parent != null)
                   {
                        
                       controlids = (List<ControlIDs>)Session["controlids"];
     
                       string oldID = "";
                       string newID = "";
     
     
                       foreach (var item in parent.Controls)
                       {
                           if (item.GetType() == typeof(RadNumericTextBox))
                           {
                               oldID = ((RadNumericTextBox)item).UniqueID;
                               ((RadNumericTextBox)item).ID = "Rn" + Guid.NewGuid();
                               newID = ((RadNumericTextBox)item).UniqueID;
                               ((RegularExpressionValidator)sender).ControlToValidate = ((RadNumericTextBox)item).ID;
                               break;
                           }
                           else if (item.GetType() == typeof(RadTextBox))
                           {
     
                               oldID = ((RadTextBox)item).UniqueID;
                               ((RadTextBox)item).ID = "Rt" + Guid.NewGuid();
                               newID = ((RadTextBox)item).UniqueID;
                               ((RegularExpressionValidator)sender).ControlToValidate = ((RadTextBox)item).ID;
                               break;
                           }
                       }
     
                       List<ControlIDs> newControlIDs = new List<ControlIDs>();
     
                       for (int tel = 0; tel < controlids.Count; tel++)
                       {
                           ControlIDs controlID = controlids[tel];
     
                           if (oldID == controlID.ControlID)
                           {
                               ControlIDs controlID_ = new ControlIDs();
                               controlID_.TimeInterVal = controlID.TimeInterVal;
                               controlID_.EventActivityAttributeKey = controlID.EventActivityAttributeKey;
                               controlID_.ControlID = newID;
                               newControlIDs.Add(controlID_);
                           }
                           else
                           {
                               newControlIDs.Add(controlID);
                           }
                       }
     
                       Session["controlids"] = newControlIDs;
                   }
     
     
               }
           }

    7. Save working ... TabelCell controls not empty anymore
    private void SaveData(object sender)
            {
     
     
    ...
    TableCell cellTimeInterval = Dataitem[DeepcopyColumns_[tel].UniqueName];
     
                                        foreach (Control item in cellTimeInterval.Controls)
                                        {
     
                                            try
                                            {
                                                if (item.GetType() == typeof(CheckBox))
                                                {
                                                    value = ((CheckBox)item).Checked.ToString();
                                                    break;
                                                }
                                                else if (item.GetType() == typeof(RadDatePicker))
                                                {
                                                    value = ((RadDatePicker)item).SelectedDate.ToString();
                                                    break;
                                                }
    ...
     
     
    }
  15. JJ
    JJ avatar
    21 posts
    Member since:
    Jul 2014

    Posted 22 Jul 2014 Link to this post

    I only get the old values of the controls not the new values. Why?
  16. Viktor Tachev
    Admin
    Viktor Tachev avatar
    1488 posts

    Posted 25 Jul 2014 Link to this post

    Hi,

    If you would like to create GridTemplateColumns programmatically, you need to ensure that the RadGrid is created entirely in the code-behind using the Page_Init event. If you would like to see an illustration of the approach you would fine this article interesting.

    Moreover, in case you need to add Validator controls explicitly to the inputs rendered in the grid you should use an approach similar to the one illustrated here.

    Try using similar approach to the one illustrated in the articles and you should be able to achieve the behavior you are looking for.

    Regards,
    Viktor Tachev
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
  17. JJ
    JJ avatar
    21 posts
    Member since:
    Jul 2014

    Posted 25 Jul 2014 in reply to Viktor Tachev Link to this post

    thanks mannn

    solution:


    1. Parent Page with Ajax Settings (Rad Grid Light Binding) 
       a. use Load Event and onChange events of controls to determine diffrent scenarious of child controls 
       b. Build User Control each time on its OnInit Event
    2. Child User Control (Advance Binding - OnNeedDataSource)
       a. use OnInit Event to create the columns (to deep copy from the temp GridTemplateColumn in ASP.net)
       b. use RadAjaxManagerProxy
                c. OnInit Event (build columns)
                i.   Columns must use ItemTemplate and EditTemplage in the temp GridTemplateColumn with Binding Text='<%# Bind("TimeInterval") %>' 
                ii.  Add all the diffrent controls like checkbox, radnumericbox, radtextbox, datetimepickers, combobox...
                iii. Controls must use events:
                - OnInit 
                * (set Unique Id's, but Id's must be stored in server object or session variable, becuase it must be the same on each init create)
                * (set the visibility of the Control you want to use to true and the other to false, thus if this is the dataType and control to use set the visibility to true else false
                - OnDataBinding 
                * (bind to server object with correct dataField, can get dataField from GridTemplateColumn)
                - OnPreRender 
                * (set the column and row selectable, this is important if you want to make RadGrid like Excell data input and use the EditTemplate, this is very important for saving of data)
                       - OnTextChange (validation with Session variables)
                - EditItemTemplate contains OnInit and OnTextChange events
                - ItemTemplate contains OnInit and OnDataBinding events and OnPreRender
  18. Jaya
    Jaya avatar
    81 posts
    Member since:
    Mar 2011

    Posted 11 Feb 2015 in reply to Daniel Link to this post

    Hi
    How to add Dynamically-created-textbox-in-radgrid using Client Side how will dot this
    When i Click Button I need add 2 rows with textbox in telerik grid.

  19. Viktor Tachev
    Admin
    Viktor Tachev avatar
    1488 posts

    Posted 13 Feb 2015 Link to this post

    Hello Jaya,

    I have replied to your query in the other thread you have submitted. I suggest we continue the conversation there.

    On a side note, it is recommended to avoid submitting duplicate threads. This way we will be able to keep better track of your support history and provide better answers quicker.

    Regards,
    Viktor Tachev
    Telerik
     

    Check out the Telerik Platform - the only platform that combines a rich set of UI tools with powerful cloud services to develop web, hybrid and native mobile apps.

     
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017