Adding Client Side Events on COlumns in RadGrid

6 posts, 0 answers
  1. Gotcha
    Gotcha avatar
    64 posts
    Member since:
    Sep 2009

    Posted 22 Mar 2012 Link to this post

    Hi,

    I have a RadGrid with InPlace EditMode...
    Initially the RadGrid is Empty and When I create a new record, it creates a new line with 3 fields ( in 3 columns all on the same line).
    I need to add client side Javascript to trigger a calculation... example : total price = qty x unit price...
    I store all 3 of those fields in the DB...

    This is just an small example of what I'm trying to achieve... basically, I need to have onKeyUp on the fields qty and unit price, and auto calculate total price...

    How can I achieve this?

    <telerik:GridNumericColumn HeaderText="Qty" DataField="Qty"
                    UniqueName="Qty" >
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="UnitPrice" DataField="UnitPrice UniqueName="UnitPrice"
                    DecimalDigits="2" >
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="TotalPrice" DataField="TotalPrice" UniqueName="TotalPrice"
                    DecimalDigits="2" ReadOnly="true">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>


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

    Posted 23 Mar 2012 Link to this post

    Hi Gotcha,

     

    In RadGrid the requested functionality is directly available by using GridCalculatedColumn. In GridCalculatedColumn a value that is calculated based on one or more fields and an expression that indicates how to calculate the display value. It is better not to save any derived value (here the field TotalPrice) in data base. Here is the sample code which I tried to achieve the same.

    ASPX:

    <telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false"  DataSourceID="SqlDataSource1" 
                             OnItemDataBound="RadGrid1_ItemDataBound">
               <MasterTableView CommandItemDisplay="Top"  EditMode="InPlace">
                   <Columns>
                       <telerik:GridNumericColumn HeaderText="Qty" DataField="Qty" UniqueName="Qty">
                           <ItemStyle Width="40px" />
                       </telerik:GridNumericColumn>
                       <telerik:GridNumericColumn HeaderText="UnitPrice" DataField="UnitPrice" UniqueName="UnitPrice"
                           DecimalDigits="2">
                           <ItemStyle Width="40px" />
                       </telerik:GridNumericColumn>
                      <telerik:GridCalculatedColumn UniqueName="TotalPrice" HeaderText="Calculated Column"
                           DataFields="UnitPrice, Qty" Expression='{0} * {1}'>
                       </telerik:GridCalculatedColumn>
                   </Columns>
               </MasterTableView>
             </telerik:RadGrid>

    C#:
    protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
      {
         if (e.Item is GridEditableItem && e.Item.IsInEditMode)
          {
              GridEditableItem item = (GridEditableItem)e.Item;
              RadNumericTextBox txtbox1 = (RadNumericTextBox)item["Qty"].Controls[0];
              txtbox1.Attributes.Add("OnBlur", "txtQtyBlur(this);");
              txtbox1.Attributes.Add("OnFocus", "txtQtyFocus(this,'" + item.ItemIndex + "');");
              RadNumericTextBox txtbox2 = (RadNumericTextBox)item["UnitPrice"].Controls[0];
              txtbox2.Attributes.Add("OnFocus", "txtPriceFocus(this,'" + item.ItemIndex + "');");
              txtbox2.Attributes.Add("OnBlur", "txtPriceBlur(this);");
              TableCell cell = (TableCell)item["TotalPrice"];
              RadGrid1.Controls.Add(new LiteralControl("<script type='text/javascript'>window['Totaltxtbox'] = '" + cell.ClientID + "';</script>"));
          }
      }

    Java Script:

    <script type="text/javascript">
        var txtQtyValue;
        var txtPriceValue;
        var itemIndex;
        function txtQtyBlur(sender) {
            var txtTotal = document.getElementById(window['Totaltxtbox']);
            txtQtyValue = sender.value;
            if (txtPriceValue == null) {
                var grid = $find("<%=RadGrid1.ClientID %>");
                var MasterTable = grid.get_masterTableView();
                var row = MasterTable.get_dataItems()[itemIndex];
                txtPriceValue = row.get_cell("UnitPrice").innerText;
            }
            txtTotal.innerText = parseFloat(txtQtyValue) * parseFloat(txtPriceValue);
        }
        function txtQtyFocus(sender, roxIndex) {
            itemIndex = roxIndex;
        }
        function txtPriceBlur(sender) {
            var txtTotal = document.getElementById(window['Totaltxtbox']);
            txtPriceValue = sender.value;
            if (txtQtyValue == null) {
                var grid = $find("<%=RadGrid1.ClientID %>");
                var MasterTable = grid.get_masterTableView();
                var row = MasterTable.get_dataItems()[itemIndex];
                txtQtyValue = row.get_cell("Qty").innerText;
            }
            txtTotal.innerText = parseFloat(txtQtyValue) * parseFloat(txtPriceValue);
        }
        function txtPriceFocus(sender, roxIndex) {
            itemIndex = roxIndex;
        }
      </script>

    Thanks,
    Princy.

  3. DevCraft Release
  4. Gotcha
    Gotcha avatar
    64 posts
    Member since:
    Sep 2009

    Posted 23 Mar 2012 Link to this post

    Hi Princy,

    thanks for the code... It is really helpful and taught me a few things...I can see how this could work .
    So I've applied the concept you've described here and did some modification into my real scenario...a bit more complex.
    ps: I have to store the calculated values in the DB because this is a constraint I have to live with.

    However, I couldnt get throught it yet.
     1. I couldnt get an expression which involved 3 columns
    2. The row.get_cell("RentalIncome").innerText is not returning me anything...

    I'm trying to get it working with the following columns:
    - RentalIncome (eg 1000)
    - OtherRentalIncome (eg 500)
    - VacancyPercent (eg 10%)
    = (RentalIncome + OtherRentalIncome) * (VacancyPercent)/100 (eg calculated as 150)

    <telerik:RadGrid ID="grdRentalProperty" runat="server" AutoGenerateEditColumn="True"
        CellSpacing="0" GridLines="None" OnNeedDataSource="grdRentalProperty_NeedDataSource"
        ShowFooter="True" AutoGenerateColumns="False" AllowMultiRowEdit="True" OnEditCommand="grdRentalProperty_EditCommand"
        OnInsertCommand="grdRentalProperty_InsertCommand" OnItemCommand="grdRentalProperty_ItemCommand"
        OnItemDataBound="grdRentalProperty_ItemDataBound" OnUpdateCommand="grdRentalProperty_UpdateCommand">
        <ClientSettings>
            <Scrolling AllowScroll="True" UseStaticHeaders="True" />
        </ClientSettings>
        <MasterTableView TableLayout="Fixed" DataKeyNames="PERSON_ID,ASSET_ASSLIB_ID,LIAB_ASSLIB_ID,ASSLIB_COLLECTION_ID"
            ClientDataKeyNames="PERSON_ID,ASSET_ASSLIB_ID,LIAB_ASSLIB_ID,ASSLIB_COLLECTION_ID"
            ShowHeadersWhenNoRecords="true" CommandItemDisplay="Bottom" EditMode="InPlace">
            <CommandItemSettings ExportToPdfText="Export to PDF"></CommandItemSettings>
            <RowIndicatorColumn Visible="True" FilterControlAltText="Filter RowIndicator column">
            </RowIndicatorColumn>
            <ExpandCollapseColumn Visible="True" FilterControlAltText="Filter ExpandColumn column">
            </ExpandCollapseColumn>
            <Columns>
                <telerik:GridBoundColumn DataField="PERSON_ID" FilterControlAltText="Filter PersonId column"
                    UniqueName="PersonId" HeaderText="PersonId" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="ASSET_ASSLIB_ID" FilterControlAltText="Filter AssetId column"
                    UniqueName="AssetId" HeaderText="AssetId" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="LIAB_ASSLIB_ID" FilterControlAltText="Filter LiabId column"
                    UniqueName="LiabId" HeaderText="LiabId" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridBoundColumn DataField="ASSLIB_COLLECTION_ID" FilterControlAltText="Filter CollectionId column"
                    UniqueName="CollectionId" HeaderText="CollectionId" Visible="true">
                </telerik:GridBoundColumn>
                <telerik:GridNumericColumn Aggregate="Count" HeaderText="Rent" DataField="RENTAL_INCOME"
                    UniqueName="RentalIncome" DecimalDigits="2" ItemStyle-Width="20">
                    <ItemStyle Width="40px"></ItemStyle>
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="Other" DataField="OTHER_RENTAL_INCOME" UniqueName="OtherRentalIncome"
                    DecimalDigits="2" ItemStyle-Width="20">
                    <ItemStyle Width="40px"></ItemStyle>
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="% Vacancy" DataField="VACANCY_PERCENT" UniqueName="VacancyPercent">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
    <% Expression Below is wrong... and genrerates an error as illegal expression, to skip it, I've used just a total for now and replaced it by {0} + {1} , in order to test the Javascript on onKeyUp() %>
                <telerik:GridCalculatedColumn HeaderText="Vacancies" UniqueName="CalculatedVacancy"
                    DataFields="RENTAL_INCOME, OTHER_RENTAL_INCOME, VACANCY_PERCENT" Expression='({0} + {1}) * ({2} / 100) '>
                    <ItemStyle Width="40px" />
                </telerik:GridCalculatedColumn>
                <telerik:GridNumericColumn HeaderText="P+I" DataField="CREDITORS_PI" UniqueName="CreditorsPI"
                    DecimalDigits="2">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="Other" DataField="OTHER_RENTAL_EXPENSE" UniqueName="OtherRentalExpense"
                    DecimalDigits="2">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="% Ownership" DataField="OWNERSHIP_PERCENT"
                    UniqueName="OwnershipPercent" DecimalDigits="2">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="Total Inc." DataField="CALC_TOTAL_INCOME"
                    UniqueName="CalculatedTotalIncome" DecimalDigits="2" ReadOnly="true">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn HeaderText="Total Exp." DataField="CALC_TOTAL_EXPENSE"
                    UniqueName="CalculatedTotalExpense" DecimalDigits="2" ReadOnly="true">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
                <telerik:GridNumericColumn Aggregate="Sum" DataFormatString="{0:C}" FooterAggregateFormatString="<b>Net Income/Loss:</b> {0:C}"
                    HeaderText="Net" DataField="CALC_NET_INCOME" UniqueName="CalculatedNetIncome"
                    DecimalDigits="2" ReadOnly="true">
                    <ItemStyle Width="40px" />
                </telerik:GridNumericColumn>
            </Columns>
            <EditFormSettings>
                <EditColumn FilterControlAltText="Filter EditCommandColumn column">
                </EditColumn>
            </EditFormSettings>
        </MasterTableView>
        <FilterMenu EnableImageSprites="False">
        </FilterMenu>
    </telerik:RadGrid>


    My javascript is below with some console logs to allow me to trace the js calls

    function KeyUp(sender, selRowIndex) {
        console.dir(sender);
        console.log('row Index : ' + selRowIndex);
       //placeholder to hold the Calculated value in the Html
        var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);
        var txtRentIncome;
        var txtOtherIncome;
        var txtVacancyPercent;
     
        //Find Mastertable in Grid
        var grid = $find("<%=grdRentalProperty.ClientID %>");
        var MasterTable = grid.get_masterTableView();
        var row = MasterTable.get_dataItems()[selRowIndex];
        console.log('Master Table');
        console.dir(MasterTable);
        console.log('row');
        console.dir(row);
     
       // All the innerText below returns me empty string
        txtRentIncome = row.get_cell("RentalIncome").innerText;
        console.log('Rent Income:' + txtRentIncome);
        txtOtherIncome = row.get_cell("OtherRentalIncome").innerText;
        console.log('Other Income:' + txtOtherIncome);
        txtVacancyPercent = row.get_cell("VacancyPercent").innerText;
        console.log('Vacancy Percent: ' + txtVacancyPercent );
     
       // Update the placeholder using the expression below. This returns me an error
        txtCalcVacancies.innerText = (parseFloat(txtRentIncome) + parseFloat(txtOtherIncome)) * (parseFloat(txtVacancyPercent) / 100);
        console.log('Rent Income:' + txtRentIncome + 'Other Income :' + txtOtherIncome + ' Vacancy Percent ' + txtVacancyPercent + ' Calculated : ' + txtCalcVacancies.innerText);
     
    }


    The Code Behind that attaches the Javascript:

    protected void grdRentalProperty_ItemDataBound(object sender, GridItemEventArgs e)
    {
     
        //If Insert mode - initialize the fields
        //if (e.Item is IGridInsertItem)
        if (e.Item.IsInEditMode)
        {
            InstitutionBL blInst = new InstitutionBL();
            InstitutionVO voInst = blInst.GetInstitutionVO(ApplicationContext.InstitutionID);
     
            if (e.Item is GridEditableItem)
            {
                //the item is in edit mode   
                // For creating new record, the following 4 keys must be visible to choose from
                ((TextBox)((GridDataItem)e.Item)["PersonId"].Controls[0]).Visible = true;
                ((TextBox)((GridDataItem)e.Item)["PersonId"].Controls[0]).Text = _personId;
     
                //TODO: Create DDL of Asset/Liab Pair to choose from of type RealEstate/Mortgage Pair. Filter out already added Rentals (Person and AssetId Pair)
                //TODO: On Change of DDL, the LiabId and CollectionId is automatically filled. ( This value comes from PERXASSLIB for a given pair)
                ((TextBox)((GridDataItem)e.Item)["AssetId"].Controls[0]).Visible = true;
     
                ((TextBox)((GridDataItem)e.Item)["LiabId"].Controls[0]).Visible = true;
     
                ((TextBox)((GridDataItem)e.Item)["CollectionId"].Controls[0]).Visible = true;
     
                RadNumericTextBox txtRentalIncome = ((RadNumericTextBox)((GridDataItem)e.Item)["RentalIncome"].Controls[0]);
                txtRentalIncome.Attributes.Add("OnKeyup", "KeyUp(this,'" + e.Item.ItemIndex + "');");
     
                RadNumericTextBox txtOtherRentalIncome = ((RadNumericTextBox)((GridDataItem)e.Item)["OtherRentalIncome"].Controls[0]);
                txtOtherRentalIncome.Attributes.Add("OnKeyup", "KeyUp(this,'" + e.Item.ItemIndex + "');");
     
                RadNumericTextBox txtVacancyPercent = ((RadNumericTextBox)((GridDataItem)e.Item)["VacancyPercent"].Controls[0]);
                txtVacancyPercent.Text = voInst.RentalVacancyPercent.ToString();
                txtVacancyPercent.Attributes.Add("OnKeyup", "KeyUp(this,'" + e.Item.ItemIndex + "');");
     
                TableCell cellVacancy = (TableCell)((GridDataItem)e.Item)["CalculatedVacancy"];
                grdRentalProperty.Controls.Add(new LiteralControl("<script type='text/javascript'>window['txtCalcVacancies'] = '" + cellVacancy.ClientID + "';</script>"));
     
                //Populated from selected AssLibId - Exp for Liability
                ((RadNumericTextBox)((GridDataItem)e.Item)["OwnershipPercent"].Controls[0]).Text = "100";
     
                ((RadNumericTextBox)((GridDataItem)e.Item)["CalculatedTotalIncome"].Controls[0]).Text = "";
                ((RadNumericTextBox)((GridDataItem)e.Item)["CalculatedTotalExpense"].Controls[0]).Text = "";
                ((RadNumericTextBox)((GridDataItem)e.Item)["CalculatedNetIncome"].Controls[0]).Text = "";
     
     
     
            }
     
            else
            {
                //init insert operation triggered  
                // For creating new record, the following 4 keys must be visible to choose from
                ((TextBox)((GridDataInsertItem)e.Item)["PersonId"].Controls[0]).Visible = true;
                ((TextBox)((GridDataInsertItem)e.Item)["PersonId"].Controls[0]).Text = _personId;
     
                //TODO: Create DDL of Asset/Liab Pair to choose from of type RealEstate/Mortgage Pair. Filter out already added Rentals (Person and AssetId Pair)
                //TODO: On Change of DDL, the LiabId and CollectionId is automatically filled. ( This value comes from PERXASSLIB for a given pair)
                ((TextBox)((GridDataInsertItem)e.Item)["AssetId"].Controls[0]).Visible = true;
                ((TextBox)((GridDataInsertItem)e.Item)["AssetId"].Controls[0]).Text = "";
     
                ((TextBox)((GridDataInsertItem)e.Item)["LiabId"].Controls[0]).Visible = true;
                ((TextBox)((GridDataInsertItem)e.Item)["LiabId"].Controls[0]).Text = "";
     
                ((TextBox)((GridDataInsertItem)e.Item)["CollectionId"].Controls[0]).Visible = true;
                ((TextBox)((GridDataInsertItem)e.Item)["CollectionId"].Controls[0]).Text = "";
     
                RadNumericTextBox txtRentalIncome = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["RentalIncome"].Controls[0]);
                txtRentalIncome.Attributes.Add("OnKeyup", "KeyUp(this,'" + e.Item.ItemIndex + "');");
     
                RadNumericTextBox txtOtherRentalIncome = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["OtherRentalIncome"].Controls[0]);
                txtOtherRentalIncome.Attributes.Add("OnKeyup", "KeyUp(this,'" + e.Item.ItemIndex + "');");
     
                RadNumericTextBox txtVacancyPercent = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["VacancyPercent"].Controls[0]);
                txtVacancyPercent.Text = voInst.RentalVacancyPercent.ToString();
                txtVacancyPercent.Attributes.Add("OnKeyup", "KeyUp(this,'" + e.Item.ItemIndex + "');");
     
                TableCell cellVacancy = (TableCell)((GridDataInsertItem)e.Item)["CalculatedVacancy"];
                grdRentalProperty.Controls.Add(new LiteralControl("<script type='text/javascript'>window['txtCalcVacancies'] = '" + cellVacancy.ClientID + "';</script>"));
     
                //Populated from selected AssLibId - Exp for Liability
                ((RadNumericTextBox)((GridDataInsertItem)e.Item)["CreditorsPI"].Controls[0]).Text = "";
                ((RadNumericTextBox)((GridDataInsertItem)e.Item)["OtherRentalExpense"].Controls[0]).Text = "";
                ((RadNumericTextBox)((GridDataInsertItem)e.Item)["OwnershipPercent"].Controls[0]).Text = "100";
     
                ((RadNumericTextBox)((GridDataInsertItem)e.Item)["CalculatedTotalIncome"].Controls[0]).Text = "";
                ((RadNumericTextBox)((GridDataInsertItem)e.Item)["CalculatedTotalExpense"].Controls[0]).Text = "";
                ((RadNumericTextBox)((GridDataInsertItem)e.Item)["CalculatedNetIncome"].Controls[0]).Text = "";
     
            }
        }
     
        //if (e.Item is GridEditableItem && e.Item.IsInEditMode)
        //{
     
        //    //the item is in edit mode   
     
        //    GridEditableItem editedItem = e.Item as GridEditableItem;
     
        //    //do something here
     
        //}
     
        //else if ((e.Item is GridDataInsertItem) && e.Item.IsInEditMode)
        //{
     
        //    //init insert operation triggered  
     
        //}
     
        //else if (e.Item is GridDataItem)
        //{
     
        //    //the item is in regular mode
     
        //    GridDataItem dataItem = e.Item as GridDataItem;
     
        //    //do something here
     
        //}else
    }



    What am I doing wrong?
    I'm guessing if I'm able to get the actual value of RentalIncome, OtherRentalIncome and VacancyPercent... it should be ok.
    Any ideas?

  5. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 26 Mar 2012 Link to this post

    Hi Gotcha,

    1) Can you try to disabling LINQ expressions in RadGrid (set EnableLinqExpressions="False")  to see if it makes any difference?

    2) I have made some modification in the code since you are trying to access this in insert mode as well. Please check the following code.

    C#:

    protected void grdRentalProperty_ItemDataBound(object sender, GridItemEventArgs e)
      {
          if (e.Item is GridEditableItem && e.Item.IsInEditMode)
          {
              GridEditableItem editItem = (GridEditableItem)e.Item;
              RadNumericTextBox txtRentalIncome = ((RadNumericTextBox)((GridEditableItem)e.Item)["RentalIncome"].Controls[0]);
              txtRentalIncome.Attributes.Add("OnBlur", "txtRentalIncomeBlur(this,'" + editItem.ItemIndex + "');");
              
              RadNumericTextBox txtOtherRentalIncome = ((RadNumericTextBox)((GridEditableItem)e.Item)["OtherRentalIncome"].Controls[0]);
              txtOtherRentalIncome.Attributes.Add("OnBlur", "txtOtherRentalIncomeBlur(this,'" + editItem.ItemIndex + "');");
        
              RadNumericTextBox txtVacancyPercent = ((RadNumericTextBox)((GridEditableItem)e.Item)["VacancyPercent"].Controls[0]);
              txtVacancyPercent.Attributes.Add("OnBlur", "txtVacancyPercentBlur(this,'" + editItem.ItemIndex + "');");
         
              TableCell cellVacancy = (TableCell)((GridEditableItem)e.Item)["CalculatedVacancy"];
              grdRentalProperty.Controls.Add(new LiteralControl("<script type='text/javascript'>window['txtCalcVacancies'] = '" + cellVacancy.ClientID + "';</script>"));
          }
          if (e.Item is GridDataInsertItem && e.Item.OwnerTableView.IsItemInserted)
          {
              RadNumericTextBox txtRentalIncome = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["RentalIncome"].Controls[0]);
              txtRentalIncome.Attributes.Add("OnBlur", "txtRentalIncomeBlur(this);");
            
               RadNumericTextBox txtOtherRentalIncome = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["OtherRentalIncome"].Controls[0]);
               txtOtherRentalIncome.Attributes.Add("OnBlur", "txtOtherRentalIncomeBlur(this);");
           
               RadNumericTextBox txtVacancyPercent = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["VacancyPercent"].Controls[0]);
               txtVacancyPercent.Attributes.Add("OnBlur", "txtVacancyPercentBlur(this);");
           
               TableCell cellVacancy = (TableCell)((GridDataInsertItem)e.Item)["CalculatedVacancy"];
               grdRentalProperty.Controls.Add(new LiteralControl("<script type='text/javascript'>window['txtCalcVacancies'] = '" + cellVacancy.ClientID + "';</script>"));
          }
     }

    Java Script:

    <script type="text/javascript">
        var txtOtherRentalIncome;
        var txtRentalIncome;
        var txtVacancyPercent;
        function txtOtherRentalIncomeBlur(sender, rowIndex) {
            var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);
            txtOtherRentalIncome = sender.value;
            var grid = $find("<%=grdRentalProperty.ClientID %>");
            var count = $find("grdRentalProperty")._editIndexes[0];
            var MasterTable = grid.get_masterTableView();
            if (txtRentalIncome == null) {
                if (count >= 0) {
                    // grid is in edit mode
                    var row = MasterTable.get_dataItems()[rowIndex];
                    txtRentalIncome = row.get_cell("RentalIncome").innerText;
                }
                else {
                    txtRentalIncome = 0;
                }
            }
            if (txtVacancyPercent == null) {
                if (count >= 0) {
                    // grid is in edit mode
                    var row = MasterTable.get_dataItems()[rowIndex];
                    txtVacancyPercent = row.get_cell("VacancyPercent").innerText;
                }
                else
                    txtVacancyPercent = 0;
            }
            txtCalcVacancies.innerText = (parseFloat(txtRentalIncome) + parseFloat(txtOtherRentalIncome)) * (parseFloat(txtVacancyPercent) / 100);
        }
     
        function txtRentalIncomeBlur(sender, rowIndex) {
           var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);
            txtRentalIncome = sender.value;
            var grid = $find("<%=grdRentalProperty.ClientID %>");
            var count = $find("grdRentalProperty")._editIndexes[0];
            var MasterTable = grid.get_masterTableView();
            if (txtOtherRentalIncome == null) {
                if (count >= 0) {
                    // grid is in edit mode
                    var row = MasterTable.get_dataItems()[rowIndex];
                    txtOtherRentalIncome = row.get_cell("OtherRentalIncome").innerText;
                }
                else {
                    txtOtherRentalIncome = 0;
                }
            }
            if (txtVacancyPercent == null) {
                if (count >= 0) {
                    // grid is in edit mode
                    var row = MasterTable.get_dataItems()[rowIndex];
                    txtVacancyPercent = row.get_cell("VacancyPercent").innerText;
                }
                else
                    txtVacancyPercent = 0;
            }
            txtCalcVacancies.innerText = (parseFloat(txtRentalIncome) + parseFloat(txtOtherRentalIncome)) * (parseFloat(txtVacancyPercent) / 100);
        }
        function txtVacancyPercentBlur(sender, rowIndex) {
            var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);
            txtVacancyPercent = sender.value;
            var grid = $find("<%=grdRentalProperty.ClientID %>");
            var count = $find("grdRentalProperty")._editIndexes[0];
            var MasterTable = grid.get_masterTableView();
            if (txtOtherRentalIncome == null) {
                if (count >= 0) {
                    // grid is in edit mode
                    var row = MasterTable.get_dataItems()[rowIndex];
                    txtOtherRentalIncome = row.get_cell("OtherRentalIncome").innerText;
                }
                else {
                    txtOtherRentalIncome = 0;
                }
            }
            if (txtRentalIncome == null) {
                if (count >= 0) {
                    // grid is in edit mode
                    var row = MasterTable.get_dataItems()[rowIndex];
                    txtRentalIncome = row.get_cell("RentalIncome").innerText;
                }
                else
                    txtRentalIncome = 0;
            }
            txtCalcVacancies.innerText = (parseFloat(txtRentalIncome) + parseFloat(txtOtherRentalIncome)) * (parseFloat(txtVacancyPercent) / 100);
        }
    </script>

    Thanks,
    Shinu.

  6. Poojitha
    Poojitha  avatar
    1 posts
    Member since:
    Jul 2012

    Posted 13 Mar 2013 Link to this post

    HI Shinu,
     I am trying to do somehting very similar to what you have explained.The grid is in EditForm mode. I am trying to execute js code and calculate a value in a third column based off 2 differnet columns in the grid. All the columns are GridNumericColumns. I was able to acheive what I wanted in edit Mode, I have trouble doing the same in Insert mode. Based on ur example my code in itemdatabound for insert mode is not executing. And the row index in insert mode is -1. I want to access the third column as
     var row = MasterTable.get_dataItems()[rowIndex];

                    txtRentalIncome = row.get_cell("RentalIncome").innerText;

    and i am getting undefined error. Am I missing any events? Any help is appreciated.

    Code behind

     

    protected void grdRentalProperty_ItemDataBound(object sender, GridItemEventArgs e)

      {

          if (e.Item is GridEditableItem && e.Item.IsInEditMode)

          {

              GridEditableItem editItem = (GridEditableItem)e.Item;

              RadNumericTextBox txtRentalIncome = ((RadNumericTextBox)((GridEditableItem)e.Item)["RentalIncome"].Controls[0]);

              txtRentalIncome.Attributes.Add("OnBlur", "txtRentalIncomeBlur(this,'" + editItem.ItemIndex + "');");

              

              RadNumericTextBox txtOtherRentalIncome = ((RadNumericTextBox)((GridEditableItem)e.Item)["OtherRentalIncome"].Controls[0]);

              txtOtherRentalIncome.Attributes.Add("OnBlur", "txtOtherRentalIncomeBlur(this,'" + editItem.ItemIndex + "');");

        

              RadNumericTextBox txtVacancyPercent = ((RadNumericTextBox)((GridEditableItem)e.Item)["VacancyPercent"].Controls[0]);

              txtVacancyPercent.Attributes.Add("OnBlur", "txtVacancyPercentBlur(this,'" + editItem.ItemIndex + "');");

         

              TableCell cellVacancy = (TableCell)((GridEditableItem)e.Item)["CalculatedVacancy"];

              grdRentalProperty.Controls.Add(new LiteralControl("<script type='text/javascript'>window['txtCalcVacancies'] = '" + cellVacancy.ClientID + "';</script>"));

          }

          if (e.Item is GridDataInsertItem && e.Item.OwnerTableView.IsItemInserted)

          {

              RadNumericTextBox txtRentalIncome = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["RentalIncome"].Controls[0]);

              txtRentalIncome.Attributes.Add("OnBlur", "txtRentalIncomeBlur(this);");

            

               RadNumericTextBox txtOtherRentalIncome = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["OtherRentalIncome"].Controls[0]);

               txtOtherRentalIncome.Attributes.Add("OnBlur", "txtOtherRentalIncomeBlur(this);");

           

               RadNumericTextBox txtVacancyPercent = ((RadNumericTextBox)((GridDataInsertItem)e.Item)["VacancyPercent"].Controls[0]);

               txtVacancyPercent.Attributes.Add("OnBlur", "txtVacancyPercentBlur(this);");

           

               TableCell cellVacancy = (TableCell)((GridDataInsertItem)e.Item)["CalculatedVacancy"];

               grdRentalProperty.Controls.Add(new LiteralControl("<script type='text/javascript'>window['txtCalcVacancies'] = '" + cellVacancy.ClientID + "';</script>"));

          }

     }

     

    JAVA SCRIPT

    <script type="text/javascript">

        var txtOtherRentalIncome;

        var txtRentalIncome;

        var txtVacancyPercent;

        function txtOtherRentalIncomeBlur(sender, rowIndex) {

            var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);

            txtOtherRentalIncome = sender.value;

            var grid = $find("<%=grdRentalProperty.ClientID %>");

            var count = $find("grdRentalProperty")._editIndexes[0];

            var MasterTable = grid.get_masterTableView();

            if (txtRentalIncome == null) {

                if (count >= 0) {

                    // grid is in edit mode

                    var row = MasterTable.get_dataItems()[rowIndex];

                    txtRentalIncome = row.get_cell("RentalIncome").innerText;

                }

                else {

                    txtRentalIncome = 0;

                }

            }

            if (txtVacancyPercent == null) {

                if (count >= 0) {

                    // grid is in edit mode

                    var row = MasterTable.get_dataItems()[rowIndex];

                    txtVacancyPercent = row.get_cell("VacancyPercent").innerText;

                }

                else

                    txtVacancyPercent = 0;

            }

            txtCalcVacancies.innerText = (parseFloat(txtRentalIncome) + parseFloat(txtOtherRentalIncome)) * (parseFloat(txtVacancyPercent) / 100);

        }

     

        function txtRentalIncomeBlur(sender, rowIndex) {

           var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);

            txtRentalIncome = sender.value;

            var grid = $find("<%=grdRentalProperty.ClientID %>");

            var count = $find("grdRentalProperty")._editIndexes[0];

            var MasterTable = grid.get_masterTableView();

            if (txtOtherRentalIncome == null) {

                if (count >= 0) {

                    // grid is in edit mode

                    var row = MasterTable.get_dataItems()[rowIndex];

                    txtOtherRentalIncome = row.get_cell("OtherRentalIncome").innerText;

                }

                else {

                    txtOtherRentalIncome = 0;

                }

            }

            if (txtVacancyPercent == null) {

                if (count >= 0) {

                    // grid is in edit mode

                    var row = MasterTable.get_dataItems()[rowIndex];

                    txtVacancyPercent = row.get_cell("VacancyPercent").innerText;

                }

                else

                    txtVacancyPercent = 0;

            }

            txtCalcVacancies.innerText = (parseFloat(txtRentalIncome) + parseFloat(txtOtherRentalIncome)) * (parseFloat(txtVacancyPercent) / 100);

        }

        function txtVacancyPercentBlur(sender, rowIndex) {

            var txtCalcVacancies = document.getElementById(window['txtCalcVacancies']);

            txtVacancyPercent = sender.value;

            var grid = $find("<%=grdRentalProperty.ClientID %>");

            var count = $find("grdRentalProperty")._editIndexes[0];

            var MasterTable = grid.get_masterTableView();

            if (txtOtherRentalIncome == null) {

                if (count >= 0) {

                    // grid is in edit mode

                    var row = MasterTable.get_dataItems()[rowIndex];

                    txtOtherRentalIncome = row.get_cell("OtherRentalIncome").innerText;

                }

                else {

                    txtOtherRentalIncome = 0;

                }

            }

            if (txtRentalIncome == null) {

                if (count >= 0) {

                    // grid is in edit mode

                    var row = MasterTable.get_dataItems()[rowIndex];

                    txtRentalIncome = row.get_cell("RentalIncome").innerText;

                }

                else

                    txtRentalIncome = 0;

            }

            txtCalcVacancies.innerText = (parseFloat(txtRentalIncome) + parseFloat(txtOtherRentalIncome)) * (parseFloat(txtVacancyPercent) / 100);

        }

    </script>

     

  7. Shinu
    Shinu avatar
    17764 posts
    Member since:
    Mar 2007

    Posted 22 Mar 2013 Link to this post

    Hi,

    Please take a look into the following Javacript.

    Javascript:

    <script type="text/javascript">
        function txtRentalIncomeBlur(sender, rowIndex) {
           //while the Radgrid is in Edit Mode
            ...your code
        }
        function txtRentalIncomeBlur(id) {
          //while the RadGrid is in Insert mode
            alert(id.value); //alert the RadNumericTextBox inserted text
           
        }
    </script>

    Thanks,
    Shinu.

Back to Top
DevCraft Release