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

Dynamically created textbox in RadGrid

17 Answers 532 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Clifton Brown
Top achievements
Rank 1
Clifton Brown asked on 04 Mar 2009, 02:08 PM
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

17 Answers, 1 is accepted

Sort by
0
Daniel
Telerik team
answered on 04 Mar 2009, 03:00 PM
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.
0
Clifton Brown
Top achievements
Rank 1
answered on 04 Mar 2009, 05:24 PM
You guys are awesome! that did it. I was creating my controls in ItemDataBound instead of ItemCreated.

Thanks!
0
Raj
Top achievements
Rank 1
answered on 15 Sep 2011, 01:59 PM
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.

0
Shinu
Top achievements
Rank 1
answered on 15 Sep 2011, 02:10 PM
Hello Raj,

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

Thanks,
Shinu.
0
Raj
Top achievements
Rank 1
answered on 15 Sep 2011, 02:42 PM
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.
0
Shinu
Top achievements
Rank 1
answered on 15 Sep 2011, 03:17 PM
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.
0
Nubia Stefania
Top achievements
Rank 1
answered on 28 Nov 2012, 11:02 PM
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
0
Daniel
Telerik team
answered on 03 Dec 2012, 03:17 PM
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.
0
JJ
Top achievements
Rank 2
answered on 21 Jul 2014, 04:20 PM
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?

0
Princy
Top achievements
Rank 1
answered on 22 Jul 2014, 06:27 AM
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
0
JJ
Top achievements
Rank 2
answered on 22 Jul 2014, 06:47 AM
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

0
JJ
Top achievements
Rank 2
answered on 22 Jul 2014, 08:50 AM
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;
                                            }
...
 
 
}
0
JJ
Top achievements
Rank 2
answered on 22 Jul 2014, 02:16 PM
I only get the old values of the controls not the new values. Why?
0
Viktor Tachev
Telerik team
answered on 25 Jul 2014, 11:26 AM
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.

 
0
JJ
Top achievements
Rank 2
answered on 25 Jul 2014, 01:44 PM
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
0
Jaya
Top achievements
Rank 1
answered on 11 Feb 2015, 08:36 AM
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.

0
Viktor Tachev
Telerik team
answered on 13 Feb 2015, 12:57 PM
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.

 
Tags
Grid
Asked by
Clifton Brown
Top achievements
Rank 1
Answers by
Daniel
Telerik team
Clifton Brown
Top achievements
Rank 1
Raj
Top achievements
Rank 1
Shinu
Top achievements
Rank 1
Nubia Stefania
Top achievements
Rank 1
JJ
Top achievements
Rank 2
Princy
Top achievements
Rank 1
Viktor Tachev
Telerik team
Jaya
Top achievements
Rank 1
Share this question
or