RadGrid read GridTemplateColumn

18 posts, 0 answers
  1. Sue
    Sue avatar
    7 posts
    Member since:
    Jan 2009

    Posted 09 Nov 2010 Link to this post

    I have a grid with items that are only read in code, both on client and server side and not all of them are editable by the user.

    Here is part of grid setup

     

    <telerik:RadGrid ID="RadGridM" runat="server" DataSourceID="DatabaseItem" OnPageIndexChanged="PageChange"

     

     

    AutoGenerateColumns="False" GridLines="None" AllowMultiRowSelection="true" EnableViewState="false"

     

     

    Skin="Office2007" AllowPaging="True" PageSize="25"

     

     

    AllowFilteringByColumn="True" OnPreRender="RadGridM_PreRender" >

     

     

    <Columns>

     

    <telerik:GridTemplateColumn DataField="QtyOrd"

     

     

    HeaderText="Qty Ord" ReadOnly="False" SortExpression="QtyOrd" UniqueName="QtyOrd" Visible="true" AllowFiltering="false" >

     

     

    <ItemTemplate>

     

     

    <asp:TextBox ID="txtQtyOrdI" runat="server" Text='<%# Bind( "QtyOrd") %>'

     

     

    Visible="true"></asp:TextBox>

     

    <%

    # DataBinder.Eval(Container.DataItem, "QtyOrd")%>

     

     

    </ItemTemplate>

     

     

    <EditItemTemplate>

     

     

    <asp:TextBox ID="txtQtyOrd" runat="server" Text='<%# Bind( "QtyOrd") %>' Width="10pt"></asp:TextBox>
    <asp:TableCell><asp:CustomValidator ID="Validate_Qty" runat="server" ControlToValidate="txtQtyOrd" ErrorMessage="Amount must be greater than 0." OnServerValidate="CustomValidator_Qty"></asp:CustomValidator>

     

     

    </EditItemTemplate>

     

     

    </telerik:GridTemplateColumn >

     

     

    <telerik:GridBoundColumn DataField="ItemNumber" HeaderText="Item Number" ReadOnly="True" SortExpression="ItemNumber" UniqueName="ItemNumber" Visible="true">

     

     

     

     

     

    </telerik:GridBoundColumn>

     

     

     

     

     

    </Columns>

     

     

    </mastertableview>

     

     

     

     

     

    </telerik:RadGrid>

     

     

    <asp:Button ID="Selection" runat="server" Text="Add Selected" onclick="Selection_Click" />

     

     

     


    On the server side when the user presses the Selection button I need to read all the values of each line on the RadGrid.
    I am able to get the items with a GridTemplateColumn using this code

     

     

    foreach (GridDataItem item1 in RadGridM.Items)

     

    {

     

     

    GridDataItem item = (GridDataItem)item1;

     

     

    TextBox QtyVal = item.FindControl("txtQtyOrdI") as TextBox;

     

     

    }

    This does not work for the GridTemplateColumn, ItemNumber

    I have tried getting the DataRowView, and adding the Item Template to the GridTemplateColumn, but the value or item comes back null.

    I have also tried item["ItemNumber"] and item["ItemNumber"].Control[0] 

    If I have a grid that does not allow any editing, but diplays values I need to process server side, and all items are in the form, below, how to a loop through each row on the server side and read the text from every column?

     

     

    <telerik:GridBoundColumn DataField="testvalue" HeaderText="testvalue"

     

     

    SortExpression="testvalue" UniqueName="testvalue" Visible="true" ReadOnly="True">

     

     

    </telerik:GridBoundColumn>

    I have also tried the things in this post, and they only work on an Item Template.

     

     

    http://www.telerik.com/community/forums/aspnet-ajax/grid/itemdatabound-on-gridtemplatecolumn.aspx

    Thanks
    Sue

     

     

     

     

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

    Posted 10 Nov 2010 Link to this post

    Hello Sue,

    Try the following approach to get the value in ItemTemplate of GridTemplateColumn.

    C#:
    protected void Selection_Click(object sender, EventArgs e)
       {
           foreach (GridDataItem item1 in RadGridM.Items)
           {
               GridDataItem item = (GridDataItem)item1;
               string QtyOrd = DataBinder.Eval(item.DataItem, "QtyOrd").ToString();// get the value in GridTemplateColumn
               string ItemNumber = item["ItemNumber"].Text; // get the value in GridBoundColumn 'ItemNumber'
           }
     
       }

    Also please go through the following documentation which explains how to access the values in grid cells.
    Accessing cells and rows

    Thanks,
    Princy.
  3. UI for ASP.NET Ajax is Ready for VS 2017
  4. Sue
    Sue avatar
    7 posts
    Member since:
    Jan 2009

    Posted 10 Nov 2010 Link to this post

    Hi Princy,

    I have already tried this method and every other one here Accessing cells and rows before posting.


    Both the lines suggested below return and "Object not set to an instance of an object" error.

    Can you provide working sample code that will read from a GridBoundColumn and GridTemplateColumn?

    Thanks
    Sue


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

    Posted 10 Nov 2010 Link to this post

    Hello Sue,

    The above code is working fine at my end. Another approach is you can use one Label inside ItemTemplate of GridTemplateColumn. Here is the sample code which shows how to loops through each grid item and access its BoundColumn and TemplateColumn's value on an external button click.

    ASPX:
    <telerik:RadGrid ID="RadGrid2" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="False">
    <MasterTableView>
    <Columns>
        <telerik:GridBoundColumn DataField="FirstName" HeaderText="FirstName" UniqueName="FirstName">
        </telerik:GridBoundColumn>
        <telerik:GridTemplateColumn>
            <ItemTemplate>
                <asp:Label ID="Label1" runat="server" Text='<%#Eval("FirstName") %>'></asp:Label>
            </ItemTemplate>
        </telerik:GridTemplateColumn>
    </Columns>
    </MasterTableView>
    </telerik:RadGrid>
     
    <br />
    <asp:Button ID="Button1" runat="server" Text="Search" onclick="Button1_Click" />

    C#:
    protected void Button1_Click(object sender, EventArgs e)
       {
           foreach (GridDataItem item in RadGrid2.Items)
           {
               string BoundColumnValue = item["FirstName"].Text; // accessing GridBoundColumn value using ColumnUniqueName
               Label lb = (Label)item.FindControl("Label1");// accessing Label control inside ItemTemplate
               string TemplateColumnValue = lb.Text;// accessing Label Text.
           }
       }

    Thanks,
    Princy.
  6. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 09 Jan 2012 Link to this post

    the text property of my cell is returning an empty string, i'm not sure why

    my markup is like

    <ItemTemplate>
    some html text including anchors, img etc. (Not server side controls)
    </ItemTemplate>

    and i'm doing

    For Each item As GridDataItem In grid.MasterTableView.Items
        Dim cell As TableCell = TryCast(item("published"), TableCell)
        cell.Text  = ...
    Next

    cell.Text is empty, i don't understand why, because.. it's not.
  7. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 09 Jan 2012 Link to this post

    fixed my issue; this removes html img from the cell. (for exporting)

                        cell = TryCast(item("published"), TableCell)     
                  For Each ctrl As DataBoundLiteralControl In cell.Controls
                            Dim strtIndex As Integer = ctrl.Text.IndexOf("<img")
                            If strtIndex > 0 Then
                                Dim endIndex As Integer = ctrl.Text.IndexOf("/>", strtIndex)

                                Dim substr As String = ctrl.Text.Substring(strtIndex, (endIndex - strtIndex) + 2)

                                cell.Text = ctrl.Text.Replace(substr, "")
                            End If
                        Next
  8. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 10 Jan 2012 Link to this post

    Thought i had fixed this but it appears not.

    infact any changes i make to the Cell.Text property do not seem to appear in the exported file, why is this ?

    For Each col As GridColumn In grid.MasterTableView.Columns
        If col.Visible Then
            Dim cell As TableCell = item(col.UniqueName)
     
            If cell.Controls.Count > 0 Then
                For Each ctrl As Control In item(col.UniqueName).Controls
                    If TypeOf (ctrl) Is DataBoundLiteralControl Then
                        Dim strtIndex As Integer = TryCast(ctrl, DataBoundLiteralControl).Text.IndexOf("<img")
                        If strtIndex > 0 Then
                            Dim endIndex As Integer = TryCast(ctrl, DataBoundLiteralControl).Text.IndexOf("/>", strtIndex)
     
                            Dim substr As String = TryCast(ctrl, DataBoundLiteralControl).Text.Substring(strtIndex, (endIndex - strtIndex) + 2)
     
                            cell.Text &= TryCast(ctrl, DataBoundLiteralControl).Text.Replace(substr, "")
     
                            cell.Text = general_functions.RemoveHTML(cell.Text.Replace("\n", "<br />"))
                            cell.Text = cell.Text.Trim.Replace("<br />", " ").Replace("€", "€")
                            cell.Text &= cell.Text.Trim
                        End If
                    End If
                Next
            Else
                Dim strtIndex As Integer = cell.Text.IndexOf("<img")
                If strtIndex > 0 Then
                    Dim endIndex As Integer = cell.Text.IndexOf("/>", strtIndex)
     
                    Dim substr As String = cell.Text.Substring(strtIndex, (endIndex - strtIndex) + 2)
     
                    cell.Text &= cell.Text.Replace(substr, "")
     
                End If
            End If
        End If
    Next
  9. Veli
    Admin
    Veli avatar
    2002 posts

    Posted 13 Jan 2012 Link to this post

    Hi Alan,

    When you have a GridTemplateColumn, the cell that has your content rendered for this column does not have its Text property set. Instead, a LiteralControl is rendered in the Controls collection of the cell and this LiteralControl contains the text in your column's ItemTemplate. If you have server controls in the ItemTemplate, they also appear in the Controls collection of your cell. So, you need to find the appropriate control and get/set its value instead of attempting to read and set the cell.Text property.

    Veli
    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
  10. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 15 Jan 2012 Link to this post

    Yeah i knew that, can you review my code above and see why it might not work ? I'm looping through the controls and building up the text property to set to the cell for when exported.
  11. Veli
    Admin
    Veli avatar
    2002 posts

    Posted 16 Jan 2012 Link to this post

    You may want to add the text you are building to a buffer string variable first, before setting the TableCell.Text property. This is because a table cell clears its controls collection if you set its text. Here is the TableCell.Text property implementation, as shown by Reflector:

    [WebSysDescription("TableCell_Text"), DefaultValue(""), PersistenceMode(PersistenceMode.InnerDefaultProperty), Localizable(true), WebCategory("Appearance")]
    public virtual string Text
    {
        get
        {
            object obj2 = this.ViewState["Text"];
            if (obj2 != null)
            {
                return (string) obj2;
            }
            return string.Empty;
        }
        set
        {
            if (this.HasControls())
            {
                this.Controls.Clear();
            }
            this.ViewState["Text"] = value;
        }
    }

    Note how the setter clears the controls collection of the table cell if you try to set its text. This means your controls may be cleared before you loop through them all.

    Veli
    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
  12. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 30 Jan 2012 Link to this post

    OK at a loss here. somehow my export is now completely blank, even though i can see whilst debugging that the cell's .Text property is being assigned.
    here's all the code
    For Each item As GridDataItem In rg_properties.MasterTableView.Items
     
         Dim datakey As DataKey = rg_properties.MasterTableView.DataKeyValues(item.ItemIndex)
     
         For Each col As GridColumn In rg_properties.MasterTableView.Columns
             If col.Visible Then
                 Dim cell As TableCell = item(col.UniqueName)
     
                 If cell.Controls.Count > 0 Then
                     Dim cellText As String = ""
                     For Each ctrl As Control In item(col.UniqueName).Controls
                         If TypeOf (ctrl) Is DataBoundLiteralControl Then
                             Dim strtIndex As Integer = TryCast(ctrl, DataBoundLiteralControl).Text.IndexOf("<img")
                             If strtIndex > 0 Then
                                 Dim endIndex As Integer = TryCast(ctrl, DataBoundLiteralControl).Text.IndexOf("/>", strtIndex)
     
                                 Dim substr As String = TryCast(ctrl, DataBoundLiteralControl).Text.Substring(strtIndex, (endIndex - strtIndex) + 2)
     
                                 cellText &= TryCast(ctrl, DataBoundLiteralControl).Text.Replace(substr, "")
                             Else
                                 cellText &= TryCast(ctrl, DataBoundLiteralControl).Text
                             End If
     
                         End If
                     Next
     
                     cellText = general_functions.RemoveHTML(cellText.Replace("\n", "<br />"))
                     cellText = cellText.Replace("<br />", " ").Replace("€", "€")
                     cellText = cellText.Trim
                     cell.Text = cellText
                 Else
                     Dim strtIndex As Integer = cell.Text.IndexOf("<img")
                     If strtIndex > 0 Then
                         Dim endIndex As Integer = cell.Text.IndexOf("/>", strtIndex)
     
                         Dim substr As String = cell.Text.Substring(strtIndex, (endIndex - strtIndex) + 2)
     
                         cell.Text = cell.Text.Replace(substr, "")
     
                     End If
                 End If
             End If
         Next
     Next
     
     If e.CommandName = Telerik.Web.UI.RadGrid.ExportToExcelCommandName Then
         rg_properties.MasterTableView.ExportToExcel()
    End If
  13. Veli
    Admin
    Veli avatar
    2002 posts

    Posted 31 Jan 2012 Link to this post

    When exporting, RadGrid rebinds automatically. This means your items and controls inside will get recreated. To replace cell text when exporting, you need to use an alternative approach. You can use the ItemCommand event in RadGrid to only raise a flag that the grid is exporting. Then you can use the ItemDataBound event to do the actual cell text formatting:

    Private exporting As Boolean = False
    Protected Sub rg_properties_ItemCommand(ByVal sender As Object, ByVal e As GridCommandEventArgs) Handles rg_properties.ItemCommand
        If e.CommandName.ToString("ExportTo") Then
            exporting = True
        End If
    End Sub
     
    Protected Sub rg_properties_ItemDataBound(ByVal sender As Object, ByVal e As GridItemEventArgs) Handles rg_properties.ItemDataBound
        If (e.Item.ItemType = GridItemType.Item Or e.Item.ItemType = GridItemType.AlternatingItem) And exporting Then
            Dim item As GridDataItem = e.Item
            'replace cell text here
        End If
    End Sub

    Using the above approach, the cell text is replaced just at the right moment.

    Veli
    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
  14. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 31 Jan 2012 Link to this post

    still not having any luck.

    Private Sub rg_properties_ItemDataBound(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridItemEventArgs) Handles rg_properties.ItemDataBound
            If (e.Item.ItemType = GridItemType.Item Or e.Item.ItemType = GridItemType.AlternatingItem) And exporting = True Then
                Dim item As GridDataItem = e.Item
     
                'replace cell text here
                For Each cell As TableCell In item.Cells
                    If cell.Visible = True Then
                        If cell.Controls.Count > 0 Then
                            Dim cellText As String = ""
                            For Each ctrl As Control In cell.Controls
                                If TypeOf (ctrl) Is DataBoundLiteralControl Then
                                    Dim strtIndex As Integer = TryCast(ctrl, DataBoundLiteralControl).Text.IndexOf("<img")
     
                                    'is there an image tag?
                                    If strtIndex > 0 Then
                                        Dim endIndex As Integer = TryCast(ctrl, DataBoundLiteralControl).Text.IndexOf("/>", strtIndex)
     
                                        Dim substr As String = TryCast(ctrl, DataBoundLiteralControl).Text.Substring(strtIndex, (endIndex - strtIndex) + 2)
     
                                        cellText &= TryCast(ctrl, DataBoundLiteralControl).Text.Replace(substr, "")
                                    Else
                                        cellText &= TryCast(ctrl, DataBoundLiteralControl).Text
                                    End If
     
                                End If
                            Next
     
                            cellText = general_functions.RemoveHTML(cellText.Replace("\n", "<br />"))
                            cellText = cellText.Replace("<br />", " ").Replace("€", "€")
                            cellText = cellText.Trim
                            cell.Text = cellText
                        Else
                            Dim strtIndex As Integer = cell.Text.IndexOf("<img")
                            'is there an image tag?
                            If strtIndex > 0 Then
                                Dim endIndex As Integer = cell.Text.IndexOf("/>", strtIndex)
     
                                Dim substr As String = cell.Text.Substring(strtIndex, (endIndex - strtIndex) + 2)
     
                                cell.Text = cell.Text.Replace(substr, "")
                            End If
                        End If
                    End If
                Next
            End If
        End Sub
  15. Alan T
    Alan T avatar
    125 posts
    Member since:
    Apr 2010

    Posted 31 Jan 2012 Link to this post

    hmm.. setting exportonlydata to false seems to result in some data being exported. although some of which i dont want.
  16. Veli
    Admin
    Veli avatar
    2002 posts

    Posted 31 Jan 2012 Link to this post

    If this issue persists, consider opening a regular support ticket where you can send us a stripped down runnable project we can debug locally. This will help us better understand your scenario and advise you further.

    Veli
    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
  17. TripDev
    TripDev avatar
    3 posts
    Member since:
    Jul 2012

    Posted 29 Aug 2013 Link to this post

    I have also been having this issue however Princy's second post worked for me.

    Thank you.
  18. Carlos
    Carlos avatar
    8 posts
    Member since:
    Dec 2012

    Posted 30 Oct 2015 in reply to TripDev Link to this post

    I'm having the same issue where the values are empty strings. but besides Princy's second post which also worded for me, I was able to get the value this way  TryCast(item("FirstName").Controls(0), textbox).text (VB).   

     (item("​FirstName").Controls(0) as textbox).text (C#)

  19. Eyup
    Admin
    Eyup avatar
    3015 posts

    Posted 03 Nov 2015 Link to this post

    Hello Carlos,

    Thank you for sharing your approach and experience with our community. I hope it may prove helpful to other developers as well.

    Regards,
    Eyup
    Telerik
    Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Feedback Portal and vote to affect the priority of the items
Back to Top
UI for ASP.NET Ajax is Ready for VS 2017