GridView calculations with JavaScript - javascript

Hi since Grid View will be rendered as table in browser
How can i apply below JavaScript on asp.net grid-view
demo on HTML table : jsfiddle
Javascript Code
Notice here calculated the grand total first then divided each row total by the grand total
<script>
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var $mult = 0;
// calculate Grand total
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
$mult += $total;
});
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
var $Percentage = (($total / $mult)).toFixed(2);
$('.percentage', this).text($Percentage);
$('.multTotal', this).text($total);
});
$("#grandTotal").text(mult);
}
});
</script>
Grid-view Code
<asp:GridView ID="testgrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtCalcQuantity" placeholder="Enter Quantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price">
<ItemTemplate>
<asp:TextBox ID="txtCalcUnitprice" placeholder="Enter Unit Price" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" runat="server" Text="0"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Percentage">
<ItemTemplate>
<asp:Label ID="lblPercentage" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Your help is much appreciated

Grid View:
<asp:GridView ID="testgrid" runat="server" AutoGenerateColumns="False" OnRowDataBound="testgrid_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="txtCalcQuantity" CssClass="val1" placeholder="Enter Quantity" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price">
<ItemTemplate>
<asp:TextBox ID="txtCalcUnitprice" CssClass="val2" placeholder="Enter Unit Price" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="lblTotal" CssClass="multTotal" runat="server" Text="0"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Percentage">
<ItemTemplate>
<asp:Label ID="lblPercentage" CssClass="percentage" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="grandTotal" runat="server"></asp:Label>
GV backend:
protected void testgrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.CssClass = "txtMult";
}
}
Javascript :
<script>
$(document).ready(function () {
$(".txtMult input").keyup(multInputs);
function multInputs() {
var $mult = 0;
// calculate Grand total
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
$mult += $total;
});
// for each row:
$("tr.txtMult").each(function () {
// get the values from this row:
var $val1 = $('.val1', this).val();
var $val2 = $('.val2', this).val();
var $total = ($val1) * ($val2);
var $Percentage = (($total / $mult)).toFixed(2);
$('.percentage', this).text($Percentage);
$('.multTotal', this).text($total);
});
$("#<%=grandTotal.ClientID %>").text($mult);
}
});

Related

how to get selected value in javascript from dropdownlist of gridview

How to retrieve the value of dropdownlist [ddrateplan] in below javascript and the dropdown is located in gridview [DataExtensionList].
<asp:GridView ID="DataExtensionList" Width="100%" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Service No.">
<ItemTemplate>
<asp:HiddenField ID="hdid" runat="server" Value='<%#Eval("tran_id") %>' />
<asp:DropDownList ID="drpphn" runat="server" CssClass="form-control" AutoPostBack="true"
OnSelectedIndexChanged="drpphn_SelectedIndexChanged" SelectedValue='<%# Eval("phone_no") %>'>
<asp:ListItem Value="0">Existing no</asp:ListItem>
<asp:ListItem Value="1">New no</asp:ListItem>
</asp:DropDownList>
<asp:TextBox ID="txtservicenumber" runat="server" Text='<%#Eval("service_number") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate Plan">
<ItemTemplate>
<asp:DropDownList ID="ddrateplan" runat="server" CssClass="form-control" AutoPostBack="true" onchange="mul();"
OnSelectedIndexChanged="ddrateplan_SelectedIndexChanged"
Style="margin: 0 !important; padding: 0 !important;" SelectedValue='<%# Eval("rate_plan") %>'>
<asp:ListItem Value="0">Select Rate Plan</asp:ListItem>
<asp:ListItem Value="35">p35</asp:ListItem>
<asp:ListItem Value="59">p59</asp:ListItem>
<asp:ListItem Value="89">p89</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<label>
<asp:TextBox ID="txt_address" AutoPostBack="true" runat="server" Text='<%# Eval("address")%>'></asp:TextBox>
</label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
this is the example of javascript i have tried but it is not working..
<script type="text/javascript">
function mul() {
var gv = document.getElementById("<%=DataExtensionList.ClientID %>");
var dropvalue = gv.getElementsByTagName('ddrateplan');
var rowcount = document.getElementById('<%=DataExtensionList.ClientID%>').rows.length;
var textmonth = document.getElementById('<%=txtcontactperiod.ClientID%>').value;
var total = 0;
for (var i = 0; i < rowcount - 1; i++) {
total += parseInt(dropvalue) * parseInt(textmonth)
}
if (textmonth > 0) {
$("<%=hdvalue.ClientID%>").val(total);
document.getElementById('<%=txttotalpayble.ClientID%>').value = total;
}
else {
$("<%=hdvalue.ClientID%>").val("");
document.getElementById('<%=txttotalpayble.ClientID%>').value = '';
}
}
</script>
i got my answer just add property of dropdown [ddrateplan] as clientidmode="static" and replace the javascript's line
var gv = document.getElementById("<%=DataExtensionList.ClientID %>");
var dropvalue = gv.getElementsByTagName('ddrateplan');
with this
var dropvalue = $("#ddrateplan").val();

Get the Div Id inside the parent GridView by Javascript

I want to get the div with id forExport and the Hidden Field Value
<table width="100%">
<tr>
<td>
<asp:HiddenField ID="hidGridView" runat="server"/>
<asp:GridView ID="grvPayroll" CssClass="table table-striped table-bordered table-hover"
AllowPaging="true"
runat="server" AutoGenerateColumns="False" DataKeyNames="Id"
OnRowCancelingEdit="grvPayroll_RowCancelingEdit" OnRowDataBound="grvPayroll_RowDataBound"
OnRowEditing="grvPayroll_RowEditing" OnRowUpdating="grvPayroll_RowUpdating"
OnRowCommand="grvPayroll_RowCommand" ShowFooter="True" OnRowDeleting="grvPayroll_RowDeleting"
OnRowDeleted="grvPayroll_RowDeleted" OnRowUpdated="grvPayroll_RowUpdated"
OnPageIndexChanging="grvPayroll_OnPageIndexChanging" PageSize="5" OnRowCreated="grvPayroll_RowCreated">
<Columns >
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:expandcollapse('div<%# Eval("Id") %>', 'one');">
<img id='imgdiv<%# Eval("Id") %>' alt="Click to show/hide Payroll Details <%# Eval("PayrollCode") %>" border="0" src="../App_Themes/Admin/img/plus.png"/>
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PayrollCode" SortExpression="PayrollCode">
<EditItemTemplate>
<asp:TextBox ID="txtPayrollCode" runat="server" Text='<%# Eval("PayrollCode") %>' CssClass="textbox"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvtxtPayrollCode"
runat="server" ControlToValidate="txtPayrollCode"
ErrorMessage="Required">
*
</asp:RequiredFieldValidator>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNewPayrollCode" runat="server" CssClass="textbox"></asp:TextBox>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblPayrollCode" runat="server" Text='<%# Bind("PayrollCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Function" ShowHeader="False">
<EditItemTemplate>
<asp:LinkButton ID="lbtUpdate" runat="server" CausesValidation="False" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="lbtCancel" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="lbtAddNew" runat="server" ToolTip="Add New" ImageUrl="../App_Themes/Admin/img/file_add.png" CausesValidation="False" CommandName="AddNew"/>
</FooterTemplate>
<ItemTemplate>
<asp:ImageButton ID="lbtEdit" runat="server" ToolTip="Edit" ImageUrl="../App_Themes/Admin/img/edit.png" CausesValidation="False" CommandName="Edit"/>
<asp:ImageButton ID="lbtDelete" runat="server" ToolTip="Delete" ImageUrl="../App_Themes/Admin/img/delete.png" OnClientClick=" return confirm('Are you sure you want to delete this?'); " CausesValidation="False" CommandName="Delete"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id='div<%# Eval("Id") %>' style="display: none; left: 15px; OVERFLOW: auto; position: relative; WIDTH: 98%">
<div id="forExport">
<asp:GridView ID="grvPayrollDetails"
EmptyDataText="No Records Found" CellPadding="5" ForeColor="#333333" GridLines="Both" AllowPaging="False"
runat="server" AutoGenerateColumns="False" DataKeyNames="PayrollID"
OnRowDataBound="grvPayrollDetails_RowDataBound" OnRowCreated="grvPayrollDetails_RowCreated">
<AlternatingRowStyle CssClass="GridStyle_AltRowStyle2"/>
<HeaderStyle CssClass="GridStyle_HeaderStyle2"/>
<RowStyle CssClass="GridStyle_RowStyle2"/>
<Columns >
<asp:TemplateField HeaderText="Mã NV">
<ItemTemplate>
<asp:Label ID="plEmpID" runat="server" Visible="false" Text='<%# Eval("EmpID").ToString() %>'></asp:Label>
<%#get_EmpCode(Eval("EmpID").ToString()) %><br/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tổng chi phí">
<ItemTemplate>
<asp:Label ID="lblTotalPaymentCost" runat="server" Text='<%#Format_Money(Eval("TotalPaymentCost").ToString()) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
And this is the script:
<script type="text/javascript">
function expandcollapse(obj, row) {
var div = document.getElementById(obj);
var img = document.getElementById("img" + obj);
if (div.style.display == "none") {
div.style.display = "block";
if (row == "alt") {
img.src = "../App_Themes/Admin/img/minus.png";
} else {
img.src = "../App_Themes/Admin/img/minus.png";
}
img.alt = "Close to view other Payroll info";
} else {
div.style.display = "none";
if (row == "alt") {
img.src = "../App_Themes/Admin/img/plus.png";
} else {
img.src = "../App_Themes/Admin/img/plus.png";
}
img.alt = "Expand to show Payroll Details";
}
}
</script>
<script type="text/javascript">
function AssignExportHTML() {
document.getElementById('<%=hidGridView.ClientID%>').value = htmlEscape(forExport.innerHTML);
}
function htmlEscape(str) {
return String(str)
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
</script>
I need to export the nested child gridview to excel with grouping (subtotal, Grand total), but when I export grouping row is only a blank row, so I try this code but it cannot work with nested gridview
So how to do, because when debugging, null value error occur. I think because Hidden Field value is null and I cannot get the div forExport in the Parent Gridview.And this is the code behind:
public override void VerifyRenderingInServerForm(Control control)
{
/* Confirms that an HtmlForm control is rendered for the specified ASP.NET
server control at run time. */
}
protected void ExportExcel(object sender, EventArgs e)
{
grvPayroll.AllowPaging = false;
var grvPayrollDetails = new GridView();
for (var i = 0; i < grvPayroll.Rows.Count; i++)
{
grvPayrollDetails = (GridView) grvPayroll.Rows[i].FindControl("grvPayrollDetails");
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=PayrollExport.xls");
Response.Charset = "UTF-8";
Response.ContentType = "application/vnd.ms-excel";
using (var sw = new StringWriter())
{
grvPayrollDetails.AllowPaging = false;
BindGrid(SortField);
grvPayrollDetails.Font.Name = "Times New Roman";
grvPayrollDetails.BackColor = Color.Transparent;
grvPayrollDetails.GridLines = GridLines.Both;
grvPayrollDetails.HeaderStyle.VerticalAlign=VerticalAlign.Middle;
sw.Write(System.Web.HttpUtility.HtmlDecode(hidGridView.Value));
Response.Write(Regex.Replace(sw.ToString(), "(<a[^>]*>)|(</a>)", " ", RegexOptions.IgnoreCase));
Response.Flush();
Response.End();
}
}
I referred this link :Exporting to Excel from GridView when grid changed by code behind
For accessing id of asp.net controls you have to use ClientID as below
document.getElementById('<%=hidGridView.ClientID%>').value = htmlEscape(document.getElementById("forExport").innerHTML);

Error: The name 'RGGSTAcCode' does not exist in the current context

In one of the webpage, I have RadGrid inside FormView Control
i.e., as below markup:
<asp:FormView ID="fvIPRForm" runat="server" DefaultMode="Insert" DataKeyNames="RequestID"
DataSourceID="odsIPRForm" EnableModelValidation="True" OnItemInserting="fvIPRForm_ItemInserting"
OnDataBound="fvIPRForm_DataBound" OnItemUpdating="fvIPRForm_Updating" OnItemCommand="fvIPRForm_ItemCommand">
<%-- Create New IPR--%>
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
<%-- Edit IPR--%>
<EditItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</EditItemTemplate>
<%-- View IPR--%>
<ItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server" SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
//RadGrid
<telerik:RadGrid ID="RGGSTAcCode" runat="server" AutoGenerateColumns="false"....>
//other code
<telerik:GridTemplateColumn UniqueName="AccountCode" HeaderText="Account Code">
<ItemTemplate>
<asp:Label ID="lblAcCode" Text='<%# Eval("AccountCode") %>' runat="server"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAcCode2" runat="server" Text='<%# Eval("AccountCode") + " - " + Eval("AccountDescription")%>' Visible="false"></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode" runat="server" Height="200" Width="260"
AllowCustomText="true" onclienttextchange="OnClientTextChange">
</telerik:RadComboBox>
<asp:Button ID="btnSearch" runat="server" Text="Search" OnClick="btnSearch_Click" OnClientClick="ButtonClicked()" UseSubmitBehavior="true" />
</EditItemTemplate>
</telerik:GridTemplateColumn>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</ItemTemplate>
</asp:FormView>
Now, I try to get the RadGrid -- EditItemTemplate -- Button control
inside JavaScript to make it visible true/false based on text length that user enter in RadComboBox.
Below is my JavaScript:
<script lang="javascript" type="text/javascript">
function OnClientTextChange(sender, eventArgs) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var form = $find("<%#RGGSTAcCode.ClientID%>").get_masterTableView();
alert(form);
}
</script>
When I run my web page, I always get below error:
The name 'RGGSTAcCode' does not exist in the current context
I tried to change the JavaScript code as below:
var form = document.getElementById('<%=fvIPRForm.FindControl("RGGSTAcCode").ClientID%>');
var masterTable = form.get_masterTableView();
alert(masterTable);
but then I get [object Object] in "alert". What is wrong in my code?
Edit
Tried below solution, all working except Buttons are not disabled/enabled inside if/else:
function onTextChange(sender, args) {
//alert("You typed " + sender.get_text());
var len = sender.get_text().length;
alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
alert("Alert 1: " + btnSearchID); //getting : contentplaceholder_fviIPRForm_RGGSTAcCode_btnSearch
var btnCtrl = $get(btnSearchID);
alert("Alert 2: " + btnCtrl); //getting : [object HTMLInputElement]
if (len > 5)
{
alert("greater");
btnCtrl.set_enabled(true);
btnsearch.set_enabled(true); // enable search button
}
else
{
alert("less");
btnCtrl.set_enabled(false);
btnsearch.set_enabled(false); // disable search button
}
}
This might be the answer you want....
Not the best but is working..
.aspx
<asp:FormView ID="fv" runat="server" DefaultMode="Insert" OnDataBound="fv_DataBound">
<InsertItemTemplate>
<telerik:RadMultiPage ID="RadMultiPage5" runat="server"
SelectedIndex="0" Width="100%">
<telerik:RadPageView ID="RadPageView4" runat="server" Width="100%">
<telerik:RadAjaxPanel ID="RadAjaxPanel4" runat="server">
<telerik:RadGrid ID="RadGrid1" runat="server"
AutoGenerateColumns="false"
OnNeedDataSource="RadGrid1_NeedDataSource">
<MasterTableView>
<Columns>
<telerik:GridTemplateColumn HeaderText="Acc">
<ItemTemplate>
<asp:Label ID="lbl" runat="server"
Text='<%# Eval("Acc") %>'></asp:Label>
<telerik:RadComboBox ID="ddlAccountCode"
runat="server" Height="200" Width="260"
AllowCustomText="true"
OnClientTextChange="onTextChange">
<Items>
<telerik:RadComboBoxItem Text="Gg" />
<telerik:RadComboBoxItem Text="Gg1" />
<telerik:RadComboBoxItem Text="Gg3" />
</Items>
</telerik:RadComboBox>
<telerik:RadButton ID="btnSearch" runat="server" Text="Search" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
</telerik:RadAjaxPanel>
</telerik:RadPageView>
</telerik:RadMultiPage>
</InsertItemTemplate>
</asp:FormView>
Javascript
<telerik:RadCodeBlock ID="rcb" runat="server">
<script type="text/javascript">
function onTextChange(sender, args) {
var grid = $find('<%=fv.FindControl("RadGrid1").ClientID %>');
var gridMasterData = grid.get_masterTableView();
var dataItem = gridMasterData.get_dataItems();
var length = dataItem.length;
// Loop
for (var i = 0; i < length; i++) {
// Find Control
var comboBox = dataItem[i].findControl("ddlAccountCode");
// Check
if (comboBox != undefined) {
if (sender.get_id() == comboBox.get_id()) {
// Find Button
var btn = dataItem[i].findControl("btnSearch");
var item = sender.get_text();
// Check
if (item.length > 5) {
if (btn != undefined) btn.set_visible(true);
}
else btn.set_visible(false);
break;
}
else
continue;
}
}
}
</script>
</telerik:RadCodeBlock>
.cs
protected void Page_Load(object sender, EventArgs e)
{
// Check
if (!IsPostBack)
{
// Variable
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
dt.Columns.Add("Acc");
dt1.Columns.Add("a");
// Loop
for (int i = 0; i < 2; i++)
dt.Rows.Add("a " + i);
dt1.Rows.Add("AAAA");
ViewState["Data"] = dt;
// Bind
fv.DataSource = dt1;
fv.DataBind();
dt.Dispose();
dt1.Dispose();
}
}
protected void fv_DataBound(object sender, EventArgs e)
{
// FindControl
RadGrid RadGrid1 = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (RadGrid1 != null)
{
RadGrid1.DataSource = ViewState["Data"] as DataTable;
RadGrid1.DataBind();
}
}
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
RadGrid rg = fv.FindControl("RadGrid1") as RadGrid;
// Check
if (rg != null)
{
rg.DataSource = ViewState["Data"] as DataTable;
}
}
Below code is working fine based on my requirement:
function onTextChange(sender, args) {
var len = sender.get_text().length;
//alert(len);
var comboID = sender.get_id();
var btnSearchID = comboID.replace("ddlAccountCode", "btnSearch");
var btnCtrl = document.getElementById(btnSearchID);
if (len >= 5)
{
btnCtrl.disabled = false;
//btnCtrl.style.display = "";
}
else
{
btnCtrl.disabled = true;
//btnCtrl.style.display = "none";
}
}

make calculation inside the gridview

I have these two itemtemplates of textboxes inside the gridview and i am trying to make calculation between them but is not working inside the grid.here is my code
<asp:TemplateField HeaderText="Net Weight">
<ItemTemplate>
<asp:TextBox ID="txtNetWT" runat="server" Width="70px" AutoPostBack=false></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="txtRate" runat="server" Width="70px" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SNF">
<ItemTemplate>
<asp:TextBox ID="txtSNF" runat="server" Width="70px" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FAT">
<ItemTemplate>
<asp:TextBox ID="txtFat" runat="server" Width="70px" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LR">
<ItemTemplate>
<asp:TextBox ID="txtLR" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="14 TS">
<ItemTemplate>
<asp:TextBox ID="txtTS" runat="server" Width="70px" ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
But When I enter the value this make no effect to other element.Please tell me any proper function in Javascript to do this.
Only change the aspx.cs page "onkeyup"
txtFATObj.Attributes.Add("onkeyup", "Calculate('" + txtFATObj.ClientID + "','" + txtSNFObj.ClientID + "','" + txtNETWTObj.ClientID + "','" + txtTSObj.ClientID + "')");
Please check the following codes. Note you need to adjust.. integer or float.. etc. I tested some calculation based on your fomula.
-- to put in javascript section inside head
<script type="text/javascript" language="javascript">
function Calculate(txtFAT, txtSNF, txtNETWT, txtTS) {
var txtFATObj = document.getElementById(txtFAT);
var txtSNFObj = document.getElementById(txtSNF);
var txtNETWTObj = document.getElementById(txtNETWT);
var txtTSObj = document.getElementById(txtTS);
if (txtFATObj != null && txtSNFObj != null && txtNETWTObj != null && txtTSObj != null) {
txtTSObj.value = parseFloat(txtFATObj.value) + (parseFloat(txtSNFObj.value) * parseFloat(txtNETWTObj.value) / 14);
}
}
</script>
--- tested gridview code aspx -----------
<asp:GridView ID="grvCalc" runat="server" AutoGenerateColumns="false"
onrowdatabound="grvCalc_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Item" DataField="Item" />
<asp:TemplateField HeaderText="Net Weight">
<ItemTemplate>
<asp:TextBox ID="txtNetWT" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:TextBox ID="txtRate" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SNF">
<ItemTemplate>
<asp:TextBox ID="txtSNF" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FAT">
<ItemTemplate>
<asp:TextBox ID="txtFat" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="LR">
<ItemTemplate>
<asp:TextBox ID="txtLR" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="14 TS">
<ItemTemplate>
<asp:TextBox ID="txtTS" runat="server" Width="70px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
---------test data bind to gridview ----------------
private void BindGridView()
{
DataTable dt = new DataTable();
dt.Columns.Add("Item");
DataRow dr = dt.NewRow();
dr[0] = "Item 1";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "Item 2";
dt.Rows.Add(dr);
dr = dt.NewRow();
dr[0] = "Item 3";
dt.Rows.Add(dr);
grvCalc.DataSource = dt;
grvCalc.DataBind();
}
-----need to attach client side event of each text control for calcuation involvement
-- gridvew row data bound event .. calculation will perform onfoucus event of text box
protected void grvCalc_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
TextBox txtFATObj = (TextBox)e.Row.FindControl("txtFAT");
TextBox txtSNFObj = (TextBox)e.Row.FindControl("txtSNF");
TextBox txtNETWTObj = (TextBox)e.Row.FindControl("txtNETWT");
TextBox txtTSObj = (TextBox)e.Row.FindControl("txtTS");
txtFATObj.Attributes.Add("onfocusout", "Calculate('" + txtFATObj.ClientID + "','" + txtSNFObj.ClientID + "','" + txtNETWTObj.ClientID + "','" + txtTSObj .ClientID + "')");
txtSNFObj.Attributes.Add("onfocusout", "Calculate('" + txtFATObj.ClientID + "','" + txtSNFObj.ClientID + "','" + txtNETWTObj.ClientID + "','" + txtTSObj.ClientID + "')");
txtNETWTObj.Attributes.Add("onfocusout", "Calculate('" + txtFATObj.ClientID + "','" + txtSNFObj.ClientID + "','" + txtNETWTObj.ClientID + "','" + txtTSObj.ClientID + "')");
}
}
This should work:
onkeydown="document.getElementById('<%= txtRate.ClientID %>').value=this.value;"

While calculating total of gridview cell using javascript and jquery getting error

I am calculating the total of GridView cells using java script and jquery. But, I am always getting this error while compiling.
The name 'total' does not exist in the
current context
Inside GridView code:
<asp:TemplateField HeaderText="Header 1">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" runat="server" Text="Total" Font-Bold="true">
</asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Header 2" >
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" class="calculate"
onchange="calculate()"></asp:TextBox>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="total" runat="server"></asp:TextBox>
</FooterTemplate>
javascript and jquery code:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"
type="text/javascript">
<script language="javascript" type="text/javascript">
function calculate()
{
var txtTotal = 0.00;
//var passed = false;
//var id = 0;
$(".calculate").each(function (index, value) {
var val = value.value;
val = val.replace(",", ".");
txtTotal = MathRound(parseFloat(txtTotal) + parseFloat(val));
});
document.getElementById("<%=total.ClientID %>").value = txtTotal.toFixed(2);
}
function MathRound(number) {
return Math.round(number * 100) / 100;
}
</script>
how can I solve this issue any help pls.
You can't access controls inside templated controls like GridView that easily. Create some variable to hold total.ClientID so that jQuery can grab it.
In your aspx:
var totalClientID = TotalClientID;
In codebehind:
void GridView1_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.Footer)
{
TotalClientID = ((TextBox)e.Row.FindControl("total")).ClientID;
}
}
<script language="javascript" type="text/javascript">
function Calculate() {
var grid = document.getElementById("<%=grid.ClientID%>");
var sum = 0;
for (var i = 1; i < grid.rows.length; i++) {
var Cell = grid.rows[i].getElementsByTagName("input");
if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[0].value);}
}
alert(sum);
}
</script>
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="txtvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="Calculate();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>`enter code here`

Categories