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

How to get the values of dynamically created controls in RadGrid ItemTemplate

5 Answers 634 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Marc
Top achievements
Rank 1
Marc asked on 02 Mar 2010, 11:16 PM
I have created a radgrid that displays labels in the first column and input controls in column 2. Column 2 can have either textbox or  DropDownList controls. What I can't figure out is how to get the values of the input controls when the form is submitted

I have tried the following but the XControl is always null. I would like to return the grid contents as XML if possible

foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
            {
                TextBox xControl = item["AttributeType"].FindControl("tb") as TextBox;
            }

Any help/ideas would greatly be appreciated!!!



ASPX Markup

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ESManager.aspx.cs" Inherits="ESManager" %>

<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server" style="height: 503px;" >
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server">
    </telerik:RadScriptManager>
      <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadGrid1">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="SpaceType" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="SpaceType">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
    <div>
    
    </div>
    <telerik:RadGrid ID="RadGrid1" runat="server" GridLines="None"
        OnItemCreated="RadGrid1_ItemCreated" Width="350px" Height="200px"  
        
        style="z-index: 1; left: 137px; top: 111px; position: absolute; height: 46px; width: 366px"
        AutoGenerateColumns="False" BorderStyle="None" >
<MasterTableView>
    <ItemTemplate>
    <%--This is required for Dynamic Creation of ItemTemplate Controls--%>
    </ItemTemplate>
    <Columns>
        <telerik:GridBoundColumn DataField="AttributeName" UniqueName="AttributeName"
            HeaderText="Space Attribute">
            <HeaderStyle Width="100px" />
        </telerik:GridBoundColumn>
        <telerik:GridBoundColumn DataField="AttributeType" UniqueName="AttributeType"
            HeaderText="Value">
            <HeaderStyle Width="75px" />
        </telerik:GridBoundColumn>
     </Columns>
</MasterTableView>
    </telerik:RadGrid>
    
    <asp:Button ID="Button1" runat="server" Text="Button"
        style="z-index: 1; left: 516px; top: 254px; position: absolute"
        onclick="Button1_Click" />
    
   
    <telerik:RadComboBox ID="SpaceType" Runat="server"
        style="z-index: 5; left: 273px; top: 63px; position: absolute; height: 22px; width: 160px; right: 486px;"
        DataSourceID="SqlDataSource1" DataTextField="Description" DataValueField="ID"
        onselectedindexchanged="SpaceType_SelectedIndexChanged"
        AutoPostBack="True">
     </telerik:RadComboBox>
     <div style="width: 231px; height: 31px; position: absolute; top: 525px; left: 13px; z-index: 1;">
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:UserConn %>"
        SelectCommand="SELECT ID,Description from SpaceTypes order by ID">
    </asp:SqlDataSource>
  </div>
     </form>
</body>
</html>

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Code Behind!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

using System;
using System.Web.UI.WebControls;
using System.Data;
using Telerik.Web.UI;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

public partial class ESManager : System.Web.UI.Page
{
    DataSet ds = new DataSet();
    
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            
        }
        else
        {
            foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
            {
                TextBox xControl = item["AttributeType"].FindControl("tb") as TextBox;
            }
        }
    }

    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
    {
        try
        {
            if (e.Item is GridDataItem)
            {

                int idex = Convert.ToInt32(e.Item.ItemIndexHierarchical);
                string type = ds.Tables[0].Rows[idex]["type"].ToString();

                Label LabelControl = new Label();
                LabelControl.ID = "l1";
                LabelControl.Text = ds.Tables[0].Rows[idex].ItemArray[0].ToString();
                LabelControl.Width = 200;
                GridDataItem item = e.Item as GridDataItem;
                item["AttributeType"].Controls.Add(LabelControl);

                if (type.ToLower() == "textbox")
                {
                    
                        TextBox xControl = new TextBox();
                        xControl.ID = "tb";
                        xControl.Text = "";
                        try { xControl.ToolTip = ds.Tables[0].Rows[idex]["doc"].ToString(); }
                        catch { }
                        xControl.Width = 75;
                        xControl.MaxLength = 7;
                        xControl.ValidationGroup = "GridControls";
                        item["AttributeType"].Controls.Add(xControl);

                        RequiredFieldValidator validator = new RequiredFieldValidator();
                        validator.ControlToValidate = xControl.ID;
                        validator.ErrorMessage = "*";

                }
                if (type.ToLower() == "listbox")
                {
                    DropDownList xControl = new DropDownList();
                    xControl.ID = "lb1";
                    string[] items = ds.Tables[0].Rows[idex]["items"].ToString().Split(',');
                    foreach (string xitem in items)
                    {
                        xControl.Items.Add(xitem);
                    }
                    xControl.SelectedValue = items[0];
                    xControl.ValidationGroup = "GridControls";
                    item["AttributeType"].Controls.Add(xControl);
                }
            }
        }
        catch (Exception ex)
        {
        }
    }
    
    protected void SpaceType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e)
    {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["UserConn"].ToString()))
        {
            SqlCommand cmd = new SqlCommand("SELECT xmlTemplate from SpaceTypes where id=@ID", conn);

            cmd.Parameters.AddWithValue("@ID", SpaceType.SelectedValue.ToString());

            conn.Open();
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                try
                {
                    StringReader strReader = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + reader["xmlTemplate"].ToString());

                    ds.ReadXml(strReader, XmlReadMode.InferSchema);
                    RadGrid1.DataSource = ds;
                    RadGrid1.DataBind();
                }
                catch (Exception ex)
                {
                }
            }
        }
    }

 
    protected void Button1_Click(object sender, EventArgs e)
    {
 
    }
}

5 Answers, 1 is accepted

Sort by
0
Princy
Top achievements
Rank 2
answered on 03 Mar 2010, 06:54 AM
Hi,

You will need to create the controls both in the ItemDataBound and ItemCreated events.This will enable you to access the controls in the a postback such as a  button click.

C#
  protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e) 
    { 
        if (e.Item is GridDataItem) 
        { 
            GridDataItem item = e.Item as GridDataItem; 
            TextBox xControl = new TextBox(); 
            xControl.ID = "tb"
            xControl.Text = ""
            xControl.Width = 75; 
            xControl.MaxLength = 7; 
            xControl.ValidationGroup = "GridControls"
            item["ProductID"].Controls.Add(xControl); 
              
 
        } 
    } 
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) 
    { 
        if (e.Item is GridDataItem) 
        { 
            GridDataItem item = e.Item as GridDataItem; 
            TextBox xControl = new TextBox(); 
            xControl.ID = "tb"
            xControl.Text = ""
            xControl.Width = 75; 
            xControl.MaxLength = 7; 
            xControl.ValidationGroup = "GridControls"
            item["ProductID"].Controls.Add(xControl); 
 
 
        } 
    } 
    protected void Button1_Click(object sender, EventArgs e) 
    { 
        foreach (GridDataItem item in RadGrid1.MasterTableView.Items) 
        { 
            TextBox xControl = item["ProductID"].FindControl("tb"as TextBox; 
        } 
    } 


Thanks,
Princy
0
Marc
Top achievements
Rank 1
answered on 03 Mar 2010, 05:11 PM
I tried your example but I still can't read values that I enter into the radgrid dynamic controls. I attached a working copy of the aspx and the code behind. Also when I use the ItemDataBound and the ItemCreated events I get duplicate controls.

----------------------------------------------------ASPX Markup-----------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ESManager.aspx.cs" Inherits="ESManager" %> 
 
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %> 
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
 
<html xmlns="http://www.w3.org/1999/xhtml"
<head runat="server"
    <title></title
    <style type="text/css"
        .style1 
        { 
            z-index: 5; 
            left: 273px; 
            top: 63px; 
            position: absolute; 
            height: 22px; 
            width: 160px; 
            right: 510px; 
        } 
    </style> 
</head> 
<body> 
    <form id="form1" runat="server" style="height: 503px;" > 
    <telerik:RadScriptManager ID="RadScriptManager1" runat="server"
    </telerik:RadScriptManager> 
      <telerik:RadAjaxManager ID="RadAjaxManager1" runat="server"
        <AjaxSettings> 
            <telerik:AjaxSetting AjaxControlID="RadGrid1"
                <UpdatedControls> 
                    <telerik:AjaxUpdatedControl ControlID="SpaceType" /> 
                </UpdatedControls> 
            </telerik:AjaxSetting> 
            <telerik:AjaxSetting AjaxControlID="SpaceType"
                <UpdatedControls> 
                    <telerik:AjaxUpdatedControl ControlID="RadGrid1" /> 
                </UpdatedControls> 
            </telerik:AjaxSetting> 
        </AjaxSettings> 
    </telerik:RadAjaxManager> 
    <div> 
     
    </div><%--OnItemCreated="RadGrid1_ItemCreated"--%>  
    <telerik:RadGrid ID="RadGrid1" runat="server" GridLines="None"  
         
        OnItemDataBound="RadGrid1_ItemDataBound" 
         Width="350px" Height="200px"   
         style="z-index: 1; left: 137px; top: 111px; position: absolute; height: 46px; width: 366px"  
        AutoGenerateColumns="False" BorderStyle="None" > 
<MasterTableView> 
    <ItemTemplate> 
    <%--This is required for Dynamic Creation of ItemTemplate Controls--%> 
    </ItemTemplate> 
    <Columns> 
        <telerik:GridBoundColumn DataField="AttributeName" UniqueName="AttributeName"  
            HeaderText="Space Attribute"
            <HeaderStyle Width="100px" /> 
        </telerik:GridBoundColumn> 
        <telerik:GridBoundColumn DataField="AttributeType" UniqueName="AttributeType"  
            HeaderText="Value"
            <HeaderStyle Width="75px" /> 
        </telerik:GridBoundColumn> 
     </Columns> 
</MasterTableView> 
    </telerik:RadGrid> 
     
    <asp:Button ID="GetGridValues" runat="server" Text="Get Grid Values"  
        style="z-index: 1; left: 516px; top: 254px; position: absolute"  
        onclick="GetGridValues_Click" /> 
     
   <telerik:RadComboBox ID="SpaceType" Runat="server"  
        onselectedindexchanged="SpaceType_SelectedIndexChanged"  
        AutoPostBack="True" CssClass="style1"
       <Items> 
           <telerik:RadComboBoxItem runat="server" Text="Select Space Type"  
               Value="Select Space Type" /> 
           <telerik:RadComboBoxItem runat="server" Text="Hotel" Value="hotel" /> 
           <telerik:RadComboBoxItem runat="server" Text="Office" Value="office" /> 
       </Items> 
     </telerik:RadComboBox> 
    
  </div> 
     </form> 
</body> 
</html> 
 
using System; 
using System.Web.UI.WebControls; 
using System.Data; 
using Telerik.Web.UI; 
using System.Data.SqlClient; 
using System.Configuration; 
using System.IO; 
 
public partial class ESManager : System.Web.UI.Page 
    DataSet ds = new DataSet(); 
     
    protected void Page_Load(object sender, EventArgs e) 
    { 
 
        if (!IsPostBack) 
        { 
             
        } 
    } 
 
    protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)  
    { 
        try 
        { 
            if (e.Item is GridDataItem) 
            { 
 
                int idex = Convert.ToInt32(e.Item.ItemIndexHierarchical); 
                string type = ds.Tables[0].Rows[idex]["type"].ToString(); 
 
                Label LabelControl = new Label(); 
                LabelControl.ID = "l1"
                LabelControl.Text = ds.Tables[0].Rows[idex].ItemArray[0].ToString(); 
                LabelControl.Width = 200; 
                GridDataItem item = e.Item as GridDataItem; 
                item["AttributeType"].Controls.Add(LabelControl); 
 
                if (type.ToLower() == "textbox"
                { 
                     
                        TextBox xControl = new TextBox(); 
                        xControl.ID = "tb"
                        xControl.Text = ""
                        try { xControl.ToolTip = ds.Tables[0].Rows[idex]["doc"].ToString(); } 
                        catch { }  
                        xControl.Width = 75; 
                        xControl.MaxLength = 7; 
                        xControl.ValidationGroup = "GridControls"
                        item["AttributeType"].Controls.Add(xControl); 
 
                        RequiredFieldValidator validator = new RequiredFieldValidator(); 
                        validator.ControlToValidate = xControl.ID; 
                        validator.ErrorMessage = "*"
 
                } 
                if (type.ToLower() == "listbox"
                { 
                    DropDownList xControl = new DropDownList(); 
                    xControl.ID = "lb1"
                    string[] items = ds.Tables[0].Rows[idex]["items"].ToString().Split(','); 
                    foreach (string xitem in items) 
                    { 
                        xControl.Items.Add(xitem); 
                    } 
                    xControl.SelectedValue = items[0]; 
                    xControl.ValidationGroup = "GridControls"
                    item["AttributeType"].Controls.Add(xControl); 
                } 
            } 
        } 
        catch (Exception ex) 
        { 
        } 
    } 
 
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e) 
    { 
        try 
        { 
            if (e.Item is GridDataItem) 
            { 
 
                int idex = Convert.ToInt32(e.Item.ItemIndexHierarchical); 
                string type = ds.Tables[0].Rows[idex]["type"].ToString(); 
 
                Label LabelControl = new Label(); 
                LabelControl.ID = "l1"
                LabelControl.Text = ds.Tables[0].Rows[idex].ItemArray[0].ToString(); 
                LabelControl.Width = 200; 
                GridDataItem item = e.Item as GridDataItem; 
                item["AttributeType"].Controls.Add(LabelControl); 
 
                if (type.ToLower() == "textbox"
                { 
 
                    TextBox xControl = new TextBox(); 
                    xControl.ID = "tb"
                    xControl.Text = ""
                    try { xControl.ToolTip = ds.Tables[0].Rows[idex]["doc"].ToString(); } 
                    catch { } 
                    xControl.Width = 75; 
                    xControl.MaxLength = 7; 
                    xControl.ValidationGroup = "GridControls"
                    item["AttributeType"].Controls.Add(xControl); 
 
                    RequiredFieldValidator validator = new RequiredFieldValidator(); 
                    validator.ControlToValidate = xControl.ID; 
                    validator.ErrorMessage = "*"
 
                } 
                if (type.ToLower() == "listbox"
                { 
                    DropDownList xControl = new DropDownList(); 
                    xControl.ID = "lb1"
                    string[] items = ds.Tables[0].Rows[idex]["items"].ToString().Split(','); 
                    foreach (string xitem in items) 
                    { 
                        xControl.Items.Add(xitem); 
                    } 
                    xControl.SelectedValue = items[0]; 
                    xControl.ValidationGroup = "GridControls"
                    item["AttributeType"].Controls.Add(xControl); 
                } 
            } 
        } 
        catch (Exception ex) 
        { 
        } 
    } 
     
    protected void SpaceType_SelectedIndexChanged(object o, RadComboBoxSelectedIndexChangedEventArgs e) 
    { 
        String tmpstr = ""
        if (SpaceType.SelectedValue.ToLower() == "hotel"
        { 
             tmpstr = "<space><Attributes><label>Gross Floor Area</label><id>hotelGrossFloorArea</id><doc>The total gross floor area (in square feet) is measured between the principal exterior surfaces of the enclosing fixed walls and includes all supporting functions.</doc><type>textbox</type><value></value></Attributes><Attributes><label>Total Rooms</label><id>hotelRooms</id><type>textbox</type><value></value></Attributes><Attributes><label>Dining Area or Kitchen</label><id>hotelFoodFacility</id><type>listbox</type><items>yes,no</items><value></value></Attributes><Attributes><label># of Feezer/Refrigerators</label><id>hotelCommercialFreezerRefrig</id><type>textbox</type><value></value></Attributes><Attributes><label># Main Shift Employees</label><id>hotelMainShiftWorkers</id><type>textbox</type><value></value></Attributes><Attributes><label>Laundry Facility</label><id>hotelLaundryFacility</id><type>listbox</type><items>yes,no</items><value></value></Attributes><Attributes><label>% Floor Space Heated</label><id>hotelGrossFloorAreaPercentHeated</id><type>textbox</type><value></value></Attributes><Attributes><label>% Floor Space Cooled</label><id>hotelGrossFloorAreaPercentCooled</id><type>textbox</type><value></value></Attributes></space>"
        } 
        if (SpaceType.SelectedValue.ToLower() == "office"
        { 
             tmpstr = "<space><Attributes><label>Gross Floor Area</label><id>officeGrossFloorSpace</id><doc>The total gross floor area (in square feet) is measured between the principal exterior surfaces of the enclosing fixed walls and includes all supporting functions.</doc><type>textbox</type><value></value></Attributes><Attributes><label>Operating Hours per Week</label><id>officeOperatingHours</id><type>textbox</type><value></value></Attributes><Attributes><label># of Office Computers</label><id>officePcs</id><type>textbox</type><value></value></Attributes><Attributes><label># Main Shift Employees</label><id>officeMainShiftWorkers</id><type>textbox</type><value></value></Attributes><Attributes><label>% Floor Space Heated</label><id>officePercentHeated</id><type>textbox</type><value></value></Attributes><Attributes><label>% Floor Space Cooled</label><id>officePercentAirConditioned</id><type>textbox</type><value></value></Attributes></space>"
        } 
 
                try 
                { 
                    StringReader strReader = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + tmpstr); 
 
                    ds.ReadXml(strReader, XmlReadMode.InferSchema); 
                    RadGrid1.DataSource = ds; 
                    RadGrid1.DataBind(); 
                } 
                catch (Exception ex) 
                { 
                } 
    } 
 
   
    protected void GetGridValues_Click(object sender, EventArgs e) 
    { 
        foreach (GridDataItem item in RadGrid1.MasterTableView.Items)  
        { 
            TextBox xControl = item["AttributeType"].FindControl("tb"as TextBox;  
        }  
    } 
 

0
JJ
Top achievements
Rank 2
answered on 23 Jul 2014, 12:47 PM
I create controls in Item-created Event and fill it with data in Item-Data-bound Event. But with Save Button Click event the new values are always overwritten with old values. I believe the Item-created and Item-Data-Bound are called before Save Button Click Event. You can use Is-post-back but I use AJAX with a user-control that I load dynamically, thus it is always a post-back. What else can I do?
0
JJ
Top achievements
Rank 2
answered on 23 Jul 2014, 02:50 PM
I played with On-Need-Data-Source event and now it only bind data once, but still no luck with getting the new values, because it calls the On-init event before save click event. In my On-init event I build the Columns Dynamically and in On-Need-Data-Source I set the data-source, then it will call Item-created<build controls> Event and Item-Data-bound<set control values> Event in the right manner. Ajax is in the parent page and the Rad-grid is in the user-control. What am I missing?
0
JJ
Top achievements
Rank 2
answered on 25 Jul 2014, 01:47 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


protected void RadDatePicker1_DataBinding(object sender, EventArgs e)
        {
            RadDatePicker box = (RadDatePicker)sender;
 
 
            GridTableCell cell = (GridTableCell)box.Parent;
            GridTemplateColumn templateColumn = (GridTemplateColumn)cell.Column;
            string timeInterVal = templateColumn.HeaderText;
            string newDataField = templateColumn.DataField;
            GridEditableItem editedItem = (GridEditableItem)box.Parent.Parent;
            //Bind Read
            try
            {
                string newValue = ((DAL.RoutineAttributeValuesWTV)editedItem.DataItem).getTimeIntervalValue(timeInterVal);
                box.SelectedDate = DateTime.Parse(newValue);
            }
            catch (Exception error) { }
            try
            {
                box.SelectedDate = (DateTime)DataBinder.Eval(editedItem.DataItem, newDataField);
            }
            catch (Exception error)
            {
                string strError = error.ToString();
                if (strError != "") { }
            }
            //Bind Update
            try
            {
                GridEditManager editMan = editedItem.EditManager;
                GridTemplateColumnEditor ColumnEditor = editMan.GetColumnEditor(templateColumn.UniqueName) as GridTemplateColumnEditor;
                var control_ = ColumnEditor.Controls;
                if (control_ != null)
                {
                    ((RadDatePicker)control_[0]).SelectedDate = (DateTime)DataBinder.Eval(editedItem.DataItem, newDataField);
                }
            }
            catch (Exception error) { }
        }
Tags
Grid
Asked by
Marc
Top achievements
Rank 1
Answers by
Princy
Top achievements
Rank 2
Marc
Top achievements
Rank 1
JJ
Top achievements
Rank 2
Share this question
or