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

Get column values from radgrid outside of grid events of client side

3 Answers 714 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Help
Top achievements
Rank 1
Help asked on 29 Aug 2018, 09:10 PM

this my aspx page

<%@ Page Title="" Language="C#" MasterPageFile="~/Modules/Module.Master" AutoEventWireup="true" CodeBehind="DataExporter.aspx.cs" Inherits="HelmOnline.Web.Modules.DataExporter.DataExporter" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ModuleHead" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ModuleContent" runat="server">

    <div style="margin: 10px; height: 100%;">

        <style type="text/css">
            .rightAlign {
                float: right;
            }

            .pad1 {
                padding-right: 20px
            }
        </style>

        <telerik:RadScriptBlock runat="server">
            <script type="text/javascript">                

                function OpenHistoryTransaction(sender, transactionid, customerid, customersetupid, employeeid) {

                    var dialogWindow = $find("<%=RadWindow1.ClientID%>");

                    if (transactionid == 0)
                    { dialogWindow.set_title("Add Transaction"); }
                    else
                    { dialogWindow.set_title("Modify Transaction"); }

                    var baseUrl = "Dialog/AddEditHistoryTransaction.aspx";
                    baseUrl = baseUrl + "?";
                    baseUrl = baseUrl + "transactionid=" + transactionid;
                    baseUrl = baseUrl + "&";
                    baseUrl = baseUrl + "customerid=" + customerid;
                    baseUrl = baseUrl + "&";
                    baseUrl = baseUrl + "customersetupid=" + customersetupid;
                    baseUrl = baseUrl + "&";
                    baseUrl = baseUrl + "employeeid=" + employeeid;
                    dialogWindow.set_navigateUrl(baseUrl)
                    dialogWindow.set_modal(true);
                    dialogWindow.show();
                }

                function OnClientCloseHandler(sender, args) {
                    var btnRefreshGrids = $find("<%=btnRefreshGrids.ClientID%>");
                    btnRefreshGrids.click();
                }

            </script>
        </telerik:RadScriptBlock>

        <telerik:RadWindowManager RenderMode="Lightweight" ID="RadWindowManager1" ShowContentDuringLoad="false" VisibleStatusbar="false" ReloadOnShow="true" runat="server" EnableShadow="true">
            <Windows>
                <telerik:RadWindow RenderMode="Lightweight" ID="RadWindow1" runat="server" Height="325" Width="525" NavigateUrl="~/Modules/PaidTimeOff/Dialog/AddEditHistoryTransaction.aspx" OnClientClose="OnClientCloseHandler" Behaviors="Close" />
            </Windows>
        </telerik:RadWindowManager>

        <telerik:RadAjaxManager ID="RadRadAjaxManager1" runat="server">
            <AjaxSettings>
                <telerik:AjaxSetting AjaxControlID="RadGrid1">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1" UpdatePanelHeight="100%" />
                        <telerik:AjaxUpdatedControl ControlID="RadGrid2" UpdatePanelHeight="100%" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
                <telerik:AjaxSetting AjaxControlID="btnRefreshGrids">
                    <UpdatedControls>
                        <telerik:AjaxUpdatedControl ControlID="btnRefreshGrids" />
                        <telerik:AjaxUpdatedControl ControlID="RadGrid1" UpdatePanelHeight="100%" />
                        <telerik:AjaxUpdatedControl ControlID="RadGrid2" UpdatePanelHeight="100%" />
                    </UpdatedControls>
                </telerik:AjaxSetting>
            </AjaxSettings>
            <ClientEvents />
        </telerik:RadAjaxManager>

        <telerik:RadAjaxPanel runat="server" ID="pDataExporter" PostBackControls="btnExportGrid" Height="100%">
            <div style="margin: 0px; height: 5%;">
                <telerik:RadButton ID="btnRefreshGrids" Text="Refresh" OnClick="btnRefreshGrids_Click" runat="server" Style="display: none;" />
                <telerik:RadButton runat="server" ID="btnExport" Text="Export Data" Visible="true" OnClick="btnExport_Click"/>
            </div>
            <div style="margin: 0px; height: 95%;" id="gridContainer">
                <div style="margin: 0px; height: 50%;">
                    <asp:ImageButton ID="btnExportGrid" runat="server" ImageUrl="/Images/Excel_XLSX.png" Height="24" Width="24" OnClick="btnExportGrid_Click" AlternateText="ExportToExcel" />
                    <telerik:RadGrid runat="server" ID="RadGrid1" Width="100%" Height="90%" AutoGenerateColumns="false" AllowPaging="False" AllowSorting="true" ShowGroupPanel="false" PageSize="10" RenderMode="Classic" AllowFilteringByColumn="true" GroupingSettings-CaseSensitive="false" OnNeedDataSource="RadGrid1_NeedDataSource" OnSelectedIndexChanged="RadGrid1_SelectedIndexChanged">
                        <MasterTableView TableLayout="Fixed">
                            <Columns>
                                <telerik:GridBoundColumn SortExpression="ExporterID" HeaderText="ExporterID" HeaderStyle-Width="0" HeaderButtonType="TextButton" DataField="ExporterID" DataFormatString="{0:d}" AllowFiltering="true" />
                                <telerik:GridBoundColumn SortExpression="StoredProcName" HeaderText="StoredProcName" HeaderStyle-Width="300" HeaderButtonType="TextButton" DataField="StoredProcName" DataFormatString="{0:d}" AllowFiltering="true" />
                                <telerik:GridBoundColumn SortExpression="Description" HeaderText="Description" HeaderButtonType="TextButton" DataField="Description" DataFormatString="{0:d}" AllowFiltering="true" />
                            </Columns>
                        </MasterTableView>
                        <ClientSettings ReorderColumnsOnClient="True" AllowDragToGroup="True" AllowColumnsReorder="True" EnablePostBackOnRowClick="true" Selecting-AllowRowSelect="true">
                            <Selecting AllowRowSelect="True"></Selecting>
                            <Resizing AllowRowResize="False" AllowColumnResize="True" EnableRealTimeResize="True" ResizeGridOnColumnResize="False"></Resizing>
                            <Scrolling UseStaticHeaders="true" AllowScroll="true" />
                        </ClientSettings>
                    </telerik:RadGrid>
                </div>
                <div style="margin: 0px; height: 50%;">
                    <telerik:RadGrid Width="100%" Height="80%" ID="RadGrid2" OnNeedDataSource="RadGrid2_NeedDataSource" OnItemDataBound="RadGrid2_ItemDataBound" runat="server" AutoGenerateColumns="false" AllowPaging="False" AllowSorting="false" ShowGroupPanel="false" PageSize="10" RenderMode="Classic" AllowFilteringByColumn="false" GroupingSettings-CaseSensitive="false">
                        <MasterTableView TableLayout="Fixed">
                            <Columns>
                                <telerik:GridBoundColumn UniqueName="NameColumn"  HeaderStyle-Width="150" SortExpression="ColumnName" HeaderText="Paramter" HeaderButtonType="TextButton" DataField="ColumnName" />
                                <telerik:GridBoundColumn UniqueName="TypeColumn"  HeaderStyle-Width="0" SortExpression="ColumnType" HeaderText="ColumnType" HeaderButtonType="TextButton" DataField="ColumnType" />
                                <telerik:GridBoundColumn UniqueName="OrderColumn" HeaderStyle-Width="0" SortExpression="ColumnOrder" HeaderText="ColumnOrder" HeaderButtonType="TextButton" DataField="ColumnOrder" />
                                <telerik:GridTemplateColumn UniqueName="ValueColumn" HeaderText="Value"/>                                
                            </Columns>
                        </MasterTableView>
                        <ClientSettings ReorderColumnsOnClient="True" AllowDragToGroup="True" AllowColumnsReorder="True" EnablePostBackOnRowClick="false">
                            <Selecting AllowRowSelect="false"></Selecting>
                            <Resizing AllowRowResize="false" AllowColumnResize="True" EnableRealTimeResize="True" ResizeGridOnColumnResize="False"></Resizing>
                            <Scrolling UseStaticHeaders="true" AllowScroll="true" />
                        </ClientSettings>
                    </telerik:RadGrid>                                        
                </div>                                                
            </div>
        </telerik:RadAjaxPanel>
    </div>    
</asp:Content>

 

This is the codebehind

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;
using xi = Telerik.Web.UI.ExportInfrastructure;
using Telerik.Web.UI.GridExcelBuilder;
using HelmOnline.Web.Common.Context;


namespace HelmOnline.Web.Modules.DataExporter
{
    public partial class DataExporter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                this.RadGrid1.Rebind();
                
            }

        }

        protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            using (var client = new svcHelm.HelmClient())
            {
                var grid = sender as RadGrid;
                grid.DataSource = client.DataExporterReportsByUserID(SecurityContext.UserId);

            }
        }

        protected void RadGrid1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GridDataItem selectedItem = (GridDataItem)RadGrid1.SelectedItems[0];
            Session["RowIndex"] = selectedItem.ItemIndex;// Gets the index of currently selected row
            this.RadGrid2.Rebind();
            RadGrid2.Visible = true;                        
        }
        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid2_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            int ExporterID = 0;
            string StoredProcName = "";
            
            if (this.RadGrid1.SelectedItems != null)
            {
                if (this.RadGrid1.SelectedItems.Count > 0)
                {
                    var selectGridItem = (Telerik.Web.UI.GridDataItem)this.RadGrid1.SelectedItems[0];
                    ExporterID = int.Parse(selectGridItem["ExporterID"].Text);
                    StoredProcName = selectGridItem["StoredProcName"].Text;
                    
                    using (var client = new svcHelm.HelmClient())
                    {
                        var grid = sender as RadGrid;
                        grid.DataSource = client.DataExporterObjectColumns(StoredProcName, SecurityContext.UserName);
                    }
                }
            }



        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnRefreshGrids_Click(object sender, EventArgs e)
        {
            string selectedEmployeeId = string.Empty;
            for (int i = 0; i < RadGrid1.Items.Count; i++)
            {
                if (RadGrid1.Items[i].Selected)
                {
                    selectedEmployeeId = RadGrid1.Items[i]["EmployeeID"].Text;
                }
            }

            this.RadGrid1.Rebind();

            if (selectedEmployeeId.Length > 0)
            {
                for (int i = 0; i < RadGrid1.Items.Count; i++)
                {
                    if (selectedEmployeeId == RadGrid1.Items[i]["EmployeeID"].Text)
                    {
                        RadGrid1.Items[i].Selected = true;
                    }
                }
            }

            this.RadGrid2.Rebind();
        }

        
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExportGrid_Click(object sender, ImageClickEventArgs e)
        {
            RadGrid1.ExportSettings.Excel.Format = (GridExcelExportFormat)Enum.Parse(typeof(GridExcelExportFormat), "Xlsx");
            RadGrid1.ExportSettings.IgnorePaging = true;
            RadGrid1.ExportSettings.ExportOnlyData = true;
            RadGrid1.ExportSettings.OpenInNewWindow = true;
            RadGrid1.MasterTableView.ExportToExcel();

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void RadGrid2_ItemDataBound(object sender, GridItemEventArgs e)
        {
            if(e.Item is GridDataItem){
                var gdi = (GridDataItem)e.Item;
                if (gdi != null){                    
                    var data = (HelmOnline.Web.svcHelm.DataExporterObjectColumn)gdi.DataItem;
                    if(data != null){
                        Control control = null;
                        switch (data.ColumnType.ToLower()){
                            case "int":
                                control = new RadNumericTextBox();
                                ((RadNumericTextBox)control).NumberFormat.DecimalDigits = 0;
                                ((RadNumericTextBox)control).ShowSpinButtons = true;                                
                                control.ID = "intControl";
                                control.DataBind();
                                break;
                            case "decimal":
                                control = new RadNumericTextBox();                                
                                control.ID = "decimalControl";
                                control.DataBind();
                                break;
                            case "money":
                                control = new RadNumericTextBox();
                                ((RadNumericTextBox)control).NumberFormat.DecimalDigits = 2;
                                ((RadNumericTextBox)control).ShowSpinButtons = true;
                                control.ID = "moneyControl";
                                control.DataBind();
                                break;
                            case "datetime":
                                control = new RadDatePicker();
                                control.ID = "datetimeControl";
                                control.DataBind();
                                break;
                            case "varchar":
                                control = new RadTextBox();
                                control.ID = "varcharControl";
                                control.DataBind();
                                break;
                            default:
                                control = new RadTextBox();
                                control.ID = "defaultControl";
                                control.DataBind();
                                break;
                        }

                        if(control != null){
                            gdi["ValueColumn"].Controls.Add(control);
                            gdi["ValueColumn"].DataBind();
                        }                        
                    }                                        
                }
            }

            
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnExport_Click(object sender, EventArgs e)
        {
            var paramDictionary = new Dictionary<string, object>();
            var grid = this.RadGrid2;
                        
            foreach (GridDataItem dataItem in grid.MasterTableView.Items){
                Control control = null;
                var pName = dataItem["NameColumn"].Text;
                var pType = dataItem["TypeColumn"].Text;
                var pOrder = int.Parse(dataItem["OrderColumn"].Text);
                object pValue = null;

                //CellValue = CType(RadGrid1.Items(i).FindControl("YourControlID"), TextBox).Text
                    //bool boolValue = (item["GridCheckBoxColumnUniqueName"].Controls[0] as CheckBox).Checked;


                switch (pType.ToLower()){
                    case "int":
                        //var column = dataItem["ValueColumn"].TemplateControl;
                        //control = column.FindControl("intControl");
                        //pValue = int.Parse(((RadNumericTextBox)control).Value.ToString());

                        var column = dataItem["ValueColumn"].Text;//value inputed by user is not here

                        //RadNumericTextBox intcontrol = (RadNumericTextBox)dataItem["ValueColumn"].FindControl("intControl");
                        RadNumericTextBox intcontrol = (RadNumericTextBox)dataItem.FindControl("intControl");

                        pValue = int.Parse(intcontrol.Value.ToString());
                        break;
                }
            }
        }
    }

}

 

I am trying to get the values of the columns of the rad grid. I can get all the static values but not the value of the template column where the user would input values.

 

 

 

3 Answers, 1 is accepted

Sort by
0
Attila Antal
Telerik team
answered on 03 Sep 2018, 04:10 PM
Hello,

I assume you would like to get the cell values of specific columns using JavaScript code from outside of the Grid events, for example clicking on a button, is that correct?

Below I will provide you with a short summary of how you can get reference to cells, columns and cell values. It is also described in details in the Client-Side Programming Overview documentation.

function MyFunction(sender, args) {
    var grid = $find('<%= RadGrid1.ClientID %>'); // reference to RadGrid
    var masterTable = grid.get_masterTableView(); // reference to MasterTableView
    var dataItems = masterTable.get_dataItems(); // get the grid rows (dataItems)
    var columns = masterTable.get_columns(); // get all the columns
    var column = columns[0]; // get reference to the first column
    var uniquName = column.get_uniqueName(); // get the column's UniqueName
    var row = dataItems[0]; // get reference to the first row in the grid
    var cell = row.get_cell(uniquName); // get the cell by column unique name
    var cellValue = cell.innerText; // get the cell value
}

Also, I have attached a sample project that demonstrates looping through the grid columns, accessing column related information, looping through grid rows, cells of rows and accessing their values.

I hope this will be helpful.

Kind regards,
Attila Antal
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
0
Help
Top achievements
Rank 1
answered on 05 Sep 2018, 04:13 PM

I do not think you understood what I was an trying to do. I am trying to get the value of the template column that the user would fill in is the code behind of the button click. This is my attempt.

protected void btnExport_Click(object sender, EventArgs e)
        {
            var paramDictionary = new Dictionary<string, object>();
            var grid = this.RadGrid2;
                        
            foreach (GridDataItem dataItem in grid.MasterTableView.Items){
                Control control = null;
                var pName = dataItem["NameColumn"].Text;
                var pType = dataItem["TypeColumn"].Text;
                var pOrder = int.Parse(dataItem["OrderColumn"].Text);
                object pValue = null;

                //CellValue = CType(RadGrid1.Items(i).FindControl("YourControlID"), TextBox).Text
                    //bool boolValue = (item["GridCheckBoxColumnUniqueName"].Controls[0] as CheckBox).Checked;


                switch (pType.ToLower()){
                    case "int":
                        //var column = dataItem["ValueColumn"].TemplateControl;
                        //control = column.FindControl("intControl");
                        //pValue = int.Parse(((RadNumericTextBox)control).Value.ToString());

                        var column = dataItem["ValueColumn"].Text;//value inputed by user is not here

                        //RadNumericTextBox intcontrol = (RadNumericTextBox)dataItem["ValueColumn"].FindControl("intControl");
                        RadNumericTextBox intcontrol = (RadNumericTextBox)dataItem.FindControl("intControl");

                        pValue = int.Parse(intcontrol.Value.ToString());
                        break;
                }
            }
        }

 

The findcontrol always come back as null. I am not sure but suspect the controls in the template column are not in the viewstate (persisted).

 

Thanks

0
Attila Antal
Telerik team
answered on 10 Sep 2018, 12:52 PM
Hello,

From the code you have shared I can see that Buttons are created and added programmatically to the grid within the ItemDataBound event. The problem is that the event fires only once when the grid is binding, every other time a postback is done the buttons will not be available on the page. When creating or changing RadGrid's structure programmatically, it is important to use the correct right event and method do it. See Creating a RadGrid Programmatically help article describing this topic.

See also: 
Later for accessing rows, cells, cell values, controls of built-in columns or well for template columns, I can recommend the the Accessing Cells and Rows article. This describes the approach for both client and server side programming. Here is another article that can be useful in your in such scenarios: Using the GetItems GetColumn and GetColumnSafe Methods.

I hope this answers your concerns.

Regards,
Attila Antal
Progress Telerik
Get quickly onboarded and successful with your Telerik and/or Kendo UI products with the Virtual Classroom free technical training, available to all active customers. Learn More.
Tags
Grid
Asked by
Help
Top achievements
Rank 1
Answers by
Attila Antal
Telerik team
Help
Top achievements
Rank 1
Share this question
or