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

innerText of editable grid cells (ReadOnly=False) contains more than just value.

7 Answers 771 Views
Grid
This is a migrated thread and some comments may be shown as answers.
Matt
Top achievements
Rank 1
Matt asked on 03 Jun 2014, 01:26 AM
According to details here: http://www.telerik.com/help/aspnet-ajax/grid-getting-cell-values-for-selected-rows-client-side.html 
in client side code I should be able to access the value of a grid cell by looking at innerHTML (and presumably innerText).
However, when I try that with cells that are editable, the cell contains data *and* hidden controls for when the row is in edit mode.

A the innerText of a cell that is in a GridDateTimeColumn willl contain
"6/12/2014\r\nRadDatePicker \r\nOpen the calendar popup.\r\n"
instead of simply "6/12/2014".
I can write a routine that parses out the values I want, but isn't there something in the Telerik client-side API that will do this?

Example:
In this client-side code, the date parsing fails because the innerText is not just the date.

function ValidateRow(rowIndex) {
 
    var rowData;
    var objCell;
    var val;
    var mtv;
    var bContinue = true;
    try {
        mtv = $find('ctl00_ContentPlaceHolder1_TestGrid').get_masterTableView();
        rowData = mtv.get_dataItems()[rowIndex];
    } catch (e) {
        bContinue = false;
    }
 
 
    // Validate Implemented Date --------------------------------------------------------------------
 
    var validDate = true;
    if (bContinue) {
        try {
            objCell = rowData.get_cell('ImplementedDate');
            val = objCell.innerText;
            var completetionDate = Date.parse(val);
...
...
...



Thanks!
-Matt


7 Answers, 1 is accepted

Sort by
0
Shinu
Top achievements
Rank 2
answered on 03 Jun 2014, 07:02 AM
Hi Matt,

In order to achieve your scenario you have to access the GridDateTimeColumn first. In your code you are accessing the particular row, so the innerText will be the data shown in that particular row. For accessing only GridDateTimeColumn value please modify your code as follows.

JavaScript:
function Validate(rowindex) {
     mtv = $find('<%=RadGrid1.ClientID%>').get_masterTableView();
     rowData = mtv.get_dataItems()[rowindex];
     // access the cell by uniquename of column
     var cell = mtv.getCellByColumnUniqueName(rowData, "OrderDate");
     var value = cell.innerText;
 }

Thanks,
Shinu.
0
Matt
Top achievements
Rank 1
answered on 03 Jun 2014, 04:39 PM
Hi Shinu. Thanks for the quick reply. Unfortunately I got the same result.
val was set to the same "5/5/2004\r\nRadDatePicker \r\nOpen the calendar popup.\r\n "
Please see modified code below.

We're using version 2013.3.1015.40 of Telerik. We haven't wanted to change versions and introduce potential UI changes to our project.
Do the cell access methods behave differently with 2014 versions?


function ValidateRow(rowIndex) {
      var rowData;
      var cell;
      var val;
      var mtv;
      var bContinue = true;
      try {
          mtv = $find('<%=TestGrid.ClientID%>').get_masterTableView();
          rowData = mtv.get_dataItems()[rowIndex];
      } catch (e) {
          bContinue = false;
      
      // Validate Implemented Date --------------------------------------------------------------------
      var validDate = true;
      if (bContinue) {
          try {
              cell = mtv.getCellByColumnUniqueName(rowData, "ImplementedDate");
              val = cell.innerText;
              var completetionDate = Date.parse(val);
              if ((completetionDate == null) || (isNaN(completetionDate))) {
                  validDate = false;
              }
              else {
                  var today = new Date();
                  if (completetionDate > today) {
                      validDate = false;
                  }
0
Shinu
Top achievements
Rank 2
answered on 04 Jun 2014, 03:12 AM
Hi Matt,

Unfortunately I couldn't replicate the issue at my end. Please have a look into the sample code snippet which works fine at my end.

ASPX:
<telerik:RadGrid ID="RadGrid1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" AutoGenerateEditColumn="true" OnItemDataBound="RadGrid1_ItemDataBound">
    <MasterTableView>
        <Columns>
            <telerik:GridBoundColumn DataField="OrderID" UniqueName="OrderID">
            </telerik:GridBoundColumn>
            <telerik:GridDateTimeColumn DataField="OrderDate" UniqueName="OrderDate">
            </telerik:GridDateTimeColumn>
        </Columns>
    </MasterTableView>
</telerik:RadGrid>

C#:
protected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)
{
    if (e.Item is GridEditableItem && e.Item.IsInEditMode)
    {
        GridEditableItem item = (GridEditableItem)e.Item;
        RadDatePicker picker = (RadDatePicker)item["OrderDate"].Controls[0];
        picker.Attributes.Add("onclick", "Validate('" + item.ItemIndex + "');");
    }
}

JavaScript:
function Validate(rowindex) {
    var rowData;
    var cell;
    var val;
    var mtv;
    var bContinue = true;
    try {
        mtv = $find('<%=RadGrid1.ClientID%>').get_masterTableView();
        rowData = mtv.get_dataItems()[rowindex];
        debugger
    } catch (e) {
        bContinue = false;
    }
    // Validate Implemented Date --------------------------------------------------------------------
    var validDate = true;
    if (bContinue) {
        cell = mtv.getCellByColumnUniqueName(rowData, "OrderDate");
        completetionDate = cell.innerText;
        if ((completetionDate == null) || (isNaN(completetionDate))) {
            validDate = false;
        }
        else {
            if (completetionDate > today) {
                var today = new Date();
                validDate = false;
            }
        }
    }
}

Please provide your full code if it doesn't help.
Thanks,
Shinu.
0
Matt
Top achievements
Rank 1
answered on 05 Jun 2014, 10:38 PM
Hi Shinu
I think the difference is in-row editing instead of the automatic form style from your example.
Also, I want to pull values from multiple cells (not just the cell the user edits) in response to the client-side OnBatchEditCellValueChanged event.

I will post full code.

Thanks
-Matt


0
Matt
Top achievements
Rank 1
answered on 05 Jun 2014, 10:40 PM
ASPX:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridTest1.aspx.cs" Inherits="ExternalNED.GridTest1" %>
  
<!DOCTYPE html>
  
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
  
  
            <style>
                /* get rid of default 300px height for scrollable grid: http://www.telerik.com/forums/excess-300px-height-in-griddata-section ; */
                .rgDataDiv {
                    height: auto !important;
                }
            </style>
  
            <telerik:RadScriptManager runat="server" ID="RadScriptManager1" />
  
            <telerik:RadGrid ID="TestGrid" runat="server" AllowMultiRowSelection="True" BackColor="pink" AutoGenerateColumns="False"
                OnNeedDataSource="TestGrid_OnNeedDataSource" OnBatchEditCommand="TestGrid_OnBatchEditCommand" OnItemDataBound="TestGrid_OnItemDataBound">
                <ClientSettings AllowColumnsReorder="true" ReorderColumnsOnClient="true" ColumnsReorderMethod="Reorder">
                    <Scrolling AllowScroll="True" UseStaticHeaders="True" FrozenColumnsCount="2"></Scrolling>
                    <%-- Note: since RowSelection event handlers use dynamically named functions, they get set in code behind, not in ClientEvents markup --%>
                    <ClientEvents OnBatchEditCellValueChanged="BatchEditCellValueChanged" />
                    <Resizing ResizeGridOnColumnResize="True"></Resizing>
                </ClientSettings>
                <MasterTableView DataKeyNames="KeyId" EditMode="Batch" AllowSorting="true">
                    <BatchEditingSettings EditType="Row" />
                    <NoRecordsTemplate>No matches found.</NoRecordsTemplate>
                    <Columns>
                        <%-- left most columns are frozen and cannot be reordered --%>
                        <telerik:GridBoundColumn Display="true" ReadOnly="True" DataField="ValidationState" HeaderText="Validation State" UniqueName="ValidationState" HeaderTooltip="Validation State." Reorderable="False" DataType="System.String"></telerik:GridBoundColumn>
                        <telerik:GridBoundColumn Display="true" ReadOnly="True" DataField="ProductName" HeaderText="Product" UniqueName="ProductName" HeaderTooltip="Product." Reorderable="False" DataType="System.String"></telerik:GridBoundColumn>
                        <%-- ^^^ frozen columns ^^^ -----------------------------------------------------------------------%>
                        <telerik:GridNumericColumn UniqueName="Quantity" DataField="Quantity" Display="true" ReadOnly="False" NumericType="Number" HeaderText="Quantity" HeaderTooltip="Quantity." DataType="System.Decimal"
                            ColumnEditorID="ShortEditbox" />
                        <telerik:GridDateTimeColumn UniqueName="EffectiveDate" DataField="EffectiveDate" Display="true" ReadOnly="True" HeaderText="Effective Date" HeaderTooltip="Effective date." DataType="System.DateTime" DataFormatString="{0:MM/dd/yyyy}"></telerik:GridDateTimeColumn>
                        <telerik:GridDateTimeColumn UniqueName="OrderDate" DataField="OrderDate" Display="true" ReadOnly="False" HeaderText="Order Date" HeaderTooltip="Order Date." DataType="System.DateTime" DataFormatString="{0:MM/dd/yyyy}"
                            ColumnEditorID="DateEditBox" />
                        <telerik:GridBoundColumn Display="true" ReadOnly="True" AllowFiltering="true" DataField="Location" HeaderText="Location" UniqueName="Location" HeaderTooltip="Location." DataType="System.String"></telerik:GridBoundColumn>
                    </Columns>
                </MasterTableView>
            </telerik:RadGrid>
            <telerik:GridNumericColumnEditor ID="ShortEditbox" runat="server">
                <NumericTextBox Width="50px" BackColor="#edffc3" NumberFormat-DecimalDigits="0" ShowSpinButtons="True" />
            </telerik:GridNumericColumnEditor>
            <telerik:GridTextBoxColumnEditor ID="WideEditbox" runat="server">
                <TextBoxStyle Width="250px" BackColor="#edffc3" />
            </telerik:GridTextBoxColumnEditor>
            <telerik:GridDateTimeColumnEditor ID="DateEditBox" runat="server">
                <%--TODO: BackColor doesn't work for date picker. Use code behind in ItemDataBound handler: http://www.telerik.com/forums/declarative-style-for-griddatetimecolumneditor ; --%>
                <TextBoxStyle Width="100px" BackColor="#edffc3" />
            </telerik:GridDateTimeColumnEditor>
  
            <br />
            <br />
  
            <div id="DbgOutput" style="width: 450px; height: 350px; overflow: auto; background-color: aqua;"></div>
              
            <br />
            <br />
  
        </div>
    </form>
  
  
    <script type="text/javascript">
          
        function BatchEditCellValueChanged(sender, args) {
            var row = args.get_row();
            var cell = args.get_cell();
            var tableView = args.get_tableView();
            var column = args.get_column();
            var columnUniqueName = args.get_columnUniqueName();
            var editorValue = args.get_editorValue();
            var cellValue = args.get_cellValue();
  
            var dataIndex = row.rowIndex - 1;
  
            var msg = "Data row:" + dataIndex + " " + columnUniqueName + " (cell " + (cell.cellIndex) + ") = " + editorValue;
            DbgPrint(msg);
  
            var batchMan = $find("<%= TestGrid.ClientID %>").get_batchEditingManager();
            // batchMan.saveChanges(tableView);
  
            ValidateRow(row.rowIndex - 1);
        }
  
        function DbgPrint(msg) {
            var dbgDiv = document.getElementById('DbgOutput');
            if (dbgDiv != null) {
                dbgDiv.innerHTML += msg + "<br/>";
  
                // scroll to bottom of debug output
                dbgDiv.scrollTop = dbgDiv.scrollHeight;
            }
  
        }
  
        function getCellValue(cell) {
            // because grid cells that are not read only have edit controls in them,
            // simply reading innerText is not enough to get values.
            // Example of date cell contents:
            // 6/12/2014\r\nRadDatePicker \r\nOpen the calendar popup.\r\n
            // Recipes from Telerik in docs and forum don't seem to work as expected:
            // http://www.telerik.com/forums/innertext-of-editable-grid-cells-(readonly=false)-contains-more-than-just-value
  
            DbgPrint("getCellValue - raw innerText: " + cell.innerText);
  
            var parts = cell.innerText.split("\r\n");
            return parts[0];
        }
  
        function ValidateRow(rowIndex) {
  
            var rowData;
            var objCell;
            var val;
            var bContinue = true;
            try {
                rowData = $find('<%=TestGrid.ClientID%>').get_masterTableView().get_dataItems()[rowIndex];
            } catch (e) {
                bContinue = false;
            }
  
  
            // Validate Order Date --------------------------------------------------------------------
  
            var validDate = true;
            if (bContinue) {
                try {
                    objCell = rowData.get_cell('OrderDate');
                    val = getCellValue(objCell);
                    var completetionDate = Date.parse(val);
  
                    if (completetionDate == null) {
                        validDate = false;
                    }
                    else {
                        var today = new Date();
                        if (completetionDate > today) {
                            validDate = false;
                        }
                        // TODO: check effective date as well
                    }
  
                } catch (e) {
                    validDate = false;
                }
  
                if (objCell != null) {
                    if (validDate) {
                        objCell.style.backgroundColor = "whitesmoke";
                    } else {
                        objCell.style.backgroundColor = "red";
                    }
                }
            }
  
            // Establish line state based on values in other cells --------------------------------------------------------------------
  
            if (bContinue) {
  
                var rowValid = validDate && true; // there will be other cell validations in the future
  
                try {
                    objCell = rowData.get_cell('ValidationState');
                    if (rowValid) {
                        objCell.style.backgroundColor = "whitesmoke";
                        objCell.innerText = "OK";
                    } else {
                        objCell.style.backgroundColor = "red";
                        objCell.innerText = "Not Ready";
                    }
  
                } catch (e) {
  
                }
            }
  
  
        }
  
  
    </script>    
  
  
  
</body>
</html>


C#:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using Telerik.Web.UI;
  
namespace ExternalNED
{
    public partial class GridTest1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
  
        }
  
        protected string DisplayUnsetDateAsBlank(string date)
        {
            // note: we're assuming that if the date is 2 digits, then it's year 0001 and not 2001 or 1901
            Regex dateNotSet = new Regex(@"^[0]{0,1}1\/[0]{0,1}1\/[0]{0,3}1$"); // matches 1/1/01, 01/01/0001, etc.
            return dateNotSet.IsMatch(date) ? String.Empty : date;
        }
  
        protected List<DataThingee> CurrentData
        {
            get
            {
                List<DataThingee> thingeeList = Session["TempDebugData"] as List<DataThingee>;
  
                if (thingeeList == null)
                {
                    thingeeList = new List<DataThingee>();
                    DataThingee newThingee;
  
                    newThingee = new DataThingee();
                    newThingee.KeyId = new Guid("4e150ccb-2ec4-e311-be01-0050569d2560");
                    newThingee.ProductName = "Toast";
                    newThingee.EffectiveDate = new DateTime(2012,6,6);
                    newThingee.Location = "downtown";
                    newThingee.OrderDate = new DateTime(2014, 6, 1);
                    thingeeList.Add(newThingee);
  
                    newThingee = new DataThingee();
                    newThingee.KeyId = new Guid("4a120ccb-2ec4-e311-be01-0050569d2560");
                    newThingee.ProductName = "Toast";
                    newThingee.EffectiveDate = new DateTime(2014, 3, 3);
                    newThingee.Location = "downtown";
                    newThingee.OrderDate = new DateTime(2014, 6, 4);
                    thingeeList.Add(newThingee);
  
                    newThingee = new DataThingee();
                    newThingee.KeyId = new Guid("ac140ccb-2ec4-e311-be01-0050569d2560");
                    newThingee.Quantity = 87;
                    newThingee.ProductName = "Llamas";
                    newThingee.EffectiveDate = new DateTime(2012, 4, 5);
                    newThingee.Location = "west hills";
                    newThingee.OrderDate = new DateTime(2014, 6, 12);
                    thingeeList.Add(newThingee);
  
                    Session["TempDebugData"] = thingeeList;
                }
  
                return thingeeList;
            }
            set
            {
                Session["TempDebugData"] = value;
            }
        }
  
        protected void TestGrid_OnNeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            TestGrid.DataSource = CurrentData;
        }
  
        protected void TestGrid_OnBatchEditCommand(object sender, GridBatchEditingEventArgs e)
        {
            foreach (GridBatchEditingCommand command in e.Commands)
            {
                Hashtable newValues = command.NewValues;
  
                string tmp = (newValues["KeyId"] != null ? newValues["KeyId"].ToString() : string.Empty);
                Guid thingeeId = Guid.Empty;
                bool bContinue = false;
                if (!string.IsNullOrWhiteSpace(tmp))
                {
                    bContinue = Guid.TryParse(tmp, out thingeeId);
                }
  
                if (bContinue)
                {
                    List<DataThingee> list = CurrentData;
                    DataThingee thingee = list.FirstOrDefault(x => x.KeyId == thingeeId);
  
                    if (thingee != null)
                    {
                        tmp = (newValues["Quantity"] != null ? newValues["Quantity"].ToString() : string.Empty);
                        if (!string.IsNullOrWhiteSpace(tmp))
                        {
                            int quantity = 0;
                            if (int.TryParse(tmp, out quantity))
                            {
                                thingee.Quantity = quantity;
                            }
                        }
  
                        tmp = (newValues["OrderDate"] != null ? newValues["OrderDate"].ToString() : string.Empty);
                        if (!string.IsNullOrWhiteSpace(tmp))
                        {
                            DateTime impDate;
                            if (DateTime.TryParse(tmp, out impDate))
                            {
                                thingee.OrderDate = impDate;
                            }
                        }
  
                    }
                }
            }
        }
  
  
        protected void TestGrid_OnItemDataBound(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridDataItem)
            {
                // Display 1/1/01 as blank.
                var dateCell = ((GridDataItem)e.Item)["OrderDate"];
                dateCell.Text = DisplayUnsetDateAsBlank(dateCell.Text);
            }
        }
  
    }
  
  
    public class DataThingee
    {
        public Guid KeyId { get; set; }
        public string ValidationState { get; set; }
        public string ProductName { get; set; }
        public int Quantity { get; set; }
        public DateTime EffectiveDate { get; set; }
        public DateTime OrderDate { get; set; }
        public string Location { get; set; }
    }
  
  
}

​
0
Accepted
Shinu
Top achievements
Rank 2
answered on 06 Jun 2014, 03:14 AM
Hi Matt,

Please do the following modification in your JavaScript to get the inner text of the DateTimeColumn.

JavaScript:
objCell = rowData.get_cell('OrderDate');
val = objCell.childNodes['0'].innerText;

Thanks,
Shinu.
0
Matt
Top achievements
Rank 1
answered on 09 Jun 2014, 05:17 PM
Hi Shinu
That will work, but the client JS code will have to know which cells are read only (and will access cell values directly via innerText) and which cells are editable (and will access cell values via child nodes).

It would be convenient if the Telerik API provided a rowData.get_cellValue('UniqueColumnName') which determined where to pull data values from automatically. Perhaps in a future release?

Thanks
-Matt
Tags
Grid
Asked by
Matt
Top achievements
Rank 1
Answers by
Shinu
Top achievements
Rank 2
Matt
Top achievements
Rank 1
Share this question
or