Get value from hidden field of ASP.Net in Javascript - javascript

<body onload="timer()">
<style type="text/css">
#time{
font-size:50pt;
}
#body
{
background-color:#F3F3F3;
}
</style>
<script type="text/javascript">
var digiclock = document.getElementById("<%= HiddenFieldMinutes.ClientID %>").value;
i = 0;
function timer() {
var digiformat = "";
if (i > 3599) {
var H = Math.floor(i / 3600);
}
else {
var H = 0;
}
var M = i - (H * 3600)
if (M > 59) {
M = Math.floor(M / 60)
}
else {
M = 0
}
var S = i - (M * 60)
if (H < 10) {
H = "0" + H;
}
if (M < 10) {
M = "0" + M;
}
if (S < 10) {
S = "0" + S;
}
document.getElementById('time').innerHTML = H + ":" + M + ":" + S;
setTimeout('timer()', 1000);
i++;
}
</script>
<table style="background-color:#F3F3F3;">
<tr>
<td><div><center><p style="font-family:Calibri;font-size:1.8em;color:#104E8B;">Total Elapsed Time</p> </center></div>
</td></tr>
<tr>
<td><div id="time"><center>90</center></div>
</td></tr>
<tr>
<td>
<center>
<form id="Form1" runat="server">
<asp:HiddenField ID="HiddenFieldMinutes" runat="server" Value="" />
<asp:Button ID="btnStop" runat="server" Text="Stop"
style="width:150px;height:30px;font-weight:bold;background-color:#104E8B;color:White;border:1px solid"
onclick="btnStop_Click" /></form></center>
<input id="HiddenTaskname" type="hidden" value="123" runat="server" />
</td></tr>
</table>
As you see above , i m trying to create a clock which starts from specified time provided by the user. I m storing the starting time period in the hidden field. The Code behind of this page load of this page is as follow:-
protected void Page_Load(object sender, EventArgs e)
{
HiddenFieldMinutes.Value = null;
if (! IsPostBack)
{
//Checking for any query string
if (Request["Code"] != null)
{
_elapsedNonProdTimeEntryID =Convert.ToInt32 (Request["Code"].ToString());
_starttime = _nonProduction.GetStartTimeOfActiveTImeEntryID(_elapsedNonProdTimeEntryID);
TimeSpan elapsedtimespan = System.DateTime.Now.Subtract(_starttime);
string hh = elapsedtimespan.Hours.ToString();
string mm = elapsedtimespan.Minutes.ToString();
string ss = elapsedtimespan.Seconds.ToString();
_differenceOfTimeSpan = hh + ":" + mm + ":" + ss;
HiddenFieldMinutes.Value = _differenceOfTimeSpan;
//ScriptManager.RegisterStartupScript(this, this.GetType(), "CloCkTImer", "javascript:timer(); ", true);
}
}
}
But when i m debugging i m getting error on this line .var digiclock = document.getElementById("<%= HiddenFieldMinutes.ClientID %>").value;
Please help me to improve this webpage and full fill my requirement.

The problem is in order of script and html elements. document.getElementById is called before html is rendered (DOM not ready yet). Just put script block after html.

I make one test which almost resembling your code,Just have a look here
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript" language="javascript">
function timer() {
alert(document.getElementById("<%= Hiddenfield1.ClientID %>").value);
}
</script>
</head>
<body onload="timer();">
<form id="form1" runat="server">
<div>
<asp:hiddenfield ID="Hiddenfield1" runat="server" value="static value"></asp:hiddenfield>
</div>
</form>
and here is CS code
protected void Page_Load(object sender, EventArgs e)
{
Hiddenfield1.Value = "dynamic value";
}
it give the Dynamic value as output.So it means your way of getting values is fine i think there is problem something else like you are trying to check hidden field value on postback or on another event if so then please take hidden field in update panel then you will get hidden field value otherwise you will remain getting the same error.
Hope it helps you.

Related

how to use javascript timer in a nested repeater?

I'm trying to add a javascript timer for products, if the item have a promotion then show the timer and start the count down.. so what i'm doing is im sending the end date from code behind to the javascript function and the function creates the timer based on the end date. I've been trying for long time the script is working, the issue is i'm not able to loop inside the nested repeater to get the correct countdown control id and index.
hope you guys can help me with this issue.
thanks
HTML Code:
<asp:Repeater runat="server" ID="Repeater1" OnItemDataBound="rptdep_ItemDataBound" OnItemCommand="rptdep_Details_Command">
<ItemTemplate>
<asp:LinkButton class="navbar-brand" runat="server" ID="LinkButton1" Style="text-decoration: none; margin-right: -25px; border: none; font-size: medium" CommandArgument='<%#Eval("department_code") %>' CommandName="more">
<asp:Repeater runat="server" ID="rptdeppromo" OnItemDataBound="rptdeppromo_ItemDataBound" OnItemCommand="Item_depPromo_Command">
<ItemTemplate>
<div runat="server" id="countdown" class="cntdwn"></div>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Timer JS code:
function producttimer(compntname, enddate1, col) {
$(document).ready(function () {
var $countdown = $('#rptdep_rptdeppromo_' + compntname + '_countdown_' + col);
// set the date we're counting down to
var target_date = new Date(enddate1);
// variables for time units
var days, hours, minutes, seconds;
// update the tag with id "countdown" every 1 second
setInterval(function () {
target_date.getTime();
// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
// check for match
if (current_date === target_date) {
}
var seconds_left = (target_date - current_date) / 1000;
// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;
minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);
// format countdown string + set tag value
$countdown.text(days + "days, " + hours + "hrs, " + minutes + "min, " + seconds + "s");
}, 1000);
}); //EOF DOCUMENT.READY
}
C# parent repeater code:
protected void rptdep_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Repeater innerRepeater2 = (Repeater)e.Item.FindControl("rptdeppromo");
DataRowView drv = (DataRowView)(e.Item.DataItem);
}
}
}
C# nested repeater code:
protected void rptdeppromo_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DataRowView drv = (DataRowView)(e.Item.DataItem);
DateTime EndDate = Convert.ToDateTime(Convert.ToDateTime(drv.Row["publishtdt"]).ToString("dd MMM yyyy"));
int countw = 0;
int count = 0;
if (total < 30)
{
count += 1;
foreach (RepeaterItem item in rptdep.Items)
{
countw += 1;
}
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "counter" + countw, "producttimer('" + countw + "','" + EndDate + "', '" + e.Item.ItemIndex + "');", true);
}
else
{
}
}
}
here is a different approach:
1- in your repeater, display all Promotions End date in label, and give them the same class "cntdwn"
2- your JS , when the page is ready it will look all items in your page with the same class and loop inside them:
var elements = document.getElementsByClassName("cntdwn");
for (var i = 0, len = elements.length; i < len; i++)
{
var PromoID = elements[i].Id;
Var EndDate = document.getElementById(PromoID).textContent;
}
3- Now you have the Lable ID , and The end Date , use your countdown logic to display the countdown in the text area of that ID.
Good luck ...
the upvoted answer worked for me, but i needed to tweak it a bit. I thought some code may help the next person who looks here.
using the plugin jquery.countup.js (any counter should work):
<div id="div<%# ((RepeaterItem)Container).ItemIndex + 1%>" class="countdown">
<%# Eval("EntryDate") %>
</div>
<script type="text/javascript">
$(function () {
var elements = document.getElementsByClassName('countdown');
var len = elements.length;
for (var i = 0; i < len; ++i) {
var timerID = elements[i].id;
var startDate = elements[i].innerText;
startCounter(startDate, timerID);
};
});
function startCounter(entryDate, timerID) {
var entDate = new Date(entryDate);
var year = (entDate).getFullYear();
var month = (entDate).getMonth() + 1;
var day = (entDate).getDate();
var hour = (entDate).getHours();
var min = (entDate).getMinutes();
var sec = (entDate).getSeconds();
$("#" + timerID).empty();
$("#" + timerID).countup({
start: new Date(year, month, day, hour, min, sec) //year, month, day, hour, min, sec
});
};

Where can I put this Javascript that references a field that hasn't been built yet?

I have a piece of JavaScript that clears out a label (well, it sets its innertext value). The problem is, after I've clicked a button and the page posts back, the label doesn't exist when the Javascript launches. So, I get an error:
0x800a138f - JavaScript runtime error: Unable to set property
'innerText' of undefined or null reference
And the code in the debug window looks like this:
.
.
<body id="PageBody" bgcolor="lightgrey">
<script type = "text/javascript">
/* Stop, Clear and Pause the timer displayed under the pause buttons */
var h1 = document.getElementsByTagName('h1')[0],
start = document.getElementById('start'),
stop = document.getElementById('stop'),
clear = document.getElementById('clear'),
seconds = 0, minutes = 0, hours = 0,
t;
function add() {
seconds++;
if (seconds >= 60) {
seconds = 0;
minutes++;
if (minutes >= 60) {
minutes = 0;
hours++;
}
}
document.getElementById('Call_Tab_TabPanelCall_h1').innerText = (hours ? (hours > 9 ? hours : "0" + hours) : "00") + ":" + (minutes ? (minutes > 9 ? minutes : "0" + minutes) : "00") + ":" + (seconds > 9 ? seconds : "0" + seconds);;
timer();
}
function timer() {
t = setTimeout(add, 1000);
}
function stp() {
clearTimeout(t);
}
function clr() {
document.getElementById('Call_Tab_TabPanelCall_h1').innerText = "00:00:00";
seconds = 0; minutes = 0; hours = 0;
}
</script>
<form method="post" action="./MedIntakeMain.aspx" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="ctl02_HiddenField" id="ctl02_HiddenField" value="" />
<input type="hidden" name="Call_Tab_ClientState" id="Call_Tab_ClientState" value="{"ActiveTabIndex":0,"TabEnabledState":[true,true],"TabWasLoadedOnceState":[true,false]}" />
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="RjVZ3Yk2xhm0S2px2EOszBEPWcGuCaATHCAyCPqZnvYuxiZww87Uj/m3sD+rm8HuCWRNiR7LvmIj0s222pyv+X/0a6tXA291/FuXA3L1zhD/Eva5aqOMBz4ruGkw38kDfwncp3DCH5V72xeLdcNEJvXVhMPxjWoQobCh6w54FD1fh9DRX7qyS6FnA+WABTw7kC95AXVYhoFgPwejgy5tqibup9SlxsRMFgrV5eJWUYsItiK5kfOtQU/e51xPqAQ8o9qck4Me71GHRPgeHgvVN9OQzNQzwfzHw8llm5vojw+FjAFrXWNxH8IkIeWpoFbHdmjnW79tToS2AVxe5jREEpa5EAujOqBg1WHtBdzpQHaMl+O3661VMjv4sKjO4eGh8ZD/3QFRQ54Du2eWPRUhaUJyHLQMy+LYVc5kSv6C2G4WZgB2Lz/wWTbuwbOXtZXqf/1v2IXfLFWRHizKsZmKGvJFKATAn6bKl94A34aJDnEIjGZXLehHyHDF+MP8GaWmNUICIUR2zKduYsvWSWkPid6DLVg07TUU82IuCbu+lASGxftlwfqMrKrlEBlsBeMFPb+7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vQVgA41TdwTrV/25gdRNJH2ExDxGN/9p/+cJ7l0OLB5zkg9j2A0+n8iqOskFpBhr+23tNmcp266nOYR15KMNRTX6FgvVTYiQVSrYWOQEhNLX4zgIij4xYkbphZkZMyC+1YBasiCzaQ4PEOXGz56y2sQ1Hsv73HsRRBaBPKHD2Hs9AOyKfqy2PnQm9FSGDxW+ZPdrTSpCX8bJcGB5sl9Mlnr9n3V2M94MZyqOu/6cUkHesB/HnyFr6/RVC1yoyNQx8iEuIEyZmp3V6GFTiHbCI9j8ErM0GhHYNJ1eFTXdZr6/Yy+yLgpZE6MfPi97H3WHM+WDvy47wys45uRvKA3BJdVsPgFyQXsOyvszWGtHFrrMgdrh05POQHUVHeMWRHG5+azuZD829uTCpWwsD4xdPNXBI13d20BHbc4ck0O/H0AaXnAk0Ia/OWmN0J01VeBqpV6ohA9FiEEdFFHbuGESVTu4DrEYQD8UeDoWquN0I4yYuiEf9+6EJ0UIZPVF/UIBKvfHyb9SmKL3Dwkx2hVH1LYneM/MFZMDBcD4vmecMYoVNoeO//tuqzFa4/aqcXGoPQ/dEanFOqs5wUI2MrEJ7iRKfXKXTdcRirCCh09KXCgEqZL3exJir2rRvM=" />
</div>
<script type="text/javascript">
//<![CDATA[
var theForm = document.forms['form1'];
if (!theForm) {
theForm = document.form1;
}
function __doPostBack(eventTarget, eventArgument) {
if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
theForm.__EVENTTARGET.value = eventTarget;
theForm.__EVENTARGUMENT.value = eventArgument;
theForm.submit();
}
}
//]]>
</script>
<script src="/WebResource.axd?d=pynGkmcFUV13He1Qd6_TZKuxqzo1qNK0jLS5vOjXgYcG0yOhGAUyRMkYR1c88uLjzDmFYO_wTSY6btwoEa6chQ2&t=635803038500000000" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
stp();clr();timer();//]]>
</
It just stops right at the </, which I guess is where the HTML would start? It's that first line in function clr that gets highlighted. If I comment out the 2 lines in function clr, everything works fine.
These functions are called using this asp on the front end:
<asp:Button ID="CallStart_Btn" runat="server" AccessKey="S" OnClick="CallStart_Btn_Click" Text="SĖ˛tart" Width="112px" OnClientClick="this.disabled=true; stp(); clr(); timer();" UseSubmitBehavior="False" style="margin-left: 0px"/>
And then in the code-behind I've got 3 lines like this:
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "stopscript", "stp();", true);
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "clearscript", "clr();", true);
ScriptManager.RegisterClientScriptBlock(UpdatePanel4, this.GetType(), "timerscript", "timer();", true);
So, where can I put that JavaScript so it will get called after the label exists?
Use
ScriptManager.RegisterStartupScript
instead of
ScriptManager.RegisterClientScriptBlock
This will put function calls at the bottom of the page.
There are a couple things at play.
You could disable/hide the button until after the label has been created (presuming some user action causes the label to appear, it could also cause the button to enable/appear).
You could add a check to each function to ensure the element exists. Something like:
function clr() {
var label = document.getElementById('Call_Tab_TabPanelCall_h1');
if(label){
label.innerText = "00:00:00";
}
seconds = 0; minutes = 0; hours = 0;
}

How to interfere to the ASPxListBox both javascript and codebehind

When I click the update button, aspxlistbox is filled by codebehind. When I print firm code to AspxTextbox4, the firm code of the firm name is displayed in the second aspxtextbox. In order to do that, I use the lostfocus event of AspxTextbox4.
However, aspxlistbox resets all data. This is an unexpected issue for me. How can I cope with that?
This is my Asp code.
<dx:ASPxTextBox ID="ASPxTextBox4" runat="server" Width="100%"
ClientInstanceName="textbox_firmcode" AutoPostBack="false" EnableClientSideAPI="true">
<ClientSideEvents LostFocus="getFirmName" />
</dx:ASPxTextBox>
<dx:ASPxButton ID="ASPxButton4" runat="server" Text="Add" Width="100%" AutoPostBack="False">
<ClientSideEvents Click="addListClick" />
</dx:ASPxButton>
<dx:ASPxListBox ID="ASPxListBox1" runat="server" Width="100%" ClientInstanceName="ASPxListBox1"> </dx:ASPxListBox>
This is the Javascript code below.
function getFirmName(s, e) {
devpopup.PerformCallback('firmtxt|' + s.GetText());
}
function addListClick(s, e) {
var firmcode = textbox_firmcode.GetText();
var firmname = textbox_firmname.GetText();
var st = 0;
for (var i = 0; i < ASPxListBox1.GetItemCount() ; i++) {
var item = ASPxListBox1.GetItem(i);
if (item.value.split(' ')[0] == firmcode) st = 1;
}
if (st == 0) {
ASPxListBox1.BeginUpdate();
ASPxListBox1.AddItem(firmcode + ' ' + firmname);
ASPxListBox1.EndUpdate();
listcount++;
}
return false;
}
The last one is the codebehind C#
protected void devpopup_WindowCallback(object source, PopupWindowCallbackArgs e)
{
string[] data = e.Parameter.Split('|');
if(data[0].Equals("firmtxt"))
{
ASPxPageControl page = (ASPxPageControl)((ASPxPopupControl)source).FindControl("ASPxPageControl1");
ASPxRoundPanel rpanel = (ASPxRoundPanel)page.FindControl("ASPxRoundPanel2");
ASPxTextBox txtbox = (ASPxTextBox)rpanel.FindControl("ASPxTextBox5");
ASPxRoundPanel otherpanel = (ASPxRoundPanel)page.FindControl("ASPxRoundPanel2");
ASPxListBox firmlistbox = (ASPxListBox)otherpanel.FindControl("ASPxListBox1");
SFADatabase db = new SFADatabase(Server);
string[] frmname = db.getData("SFA_FIRM", new string[] { "FRMNAME" }, "WHERE FRMCODE='" + data[1] + "'");
if (frmname.Length > 0)
{
txtbox.Text = frmname[0];
txtbox.Focus();
//txtbox.Enabled = false;
}
else
{
//txtbox.Enabled = true;
txtbox.Text = "";
txtbox.Focus();
}
}
}
public void putUpdateData(string parameter, object source)
{
// Load the firm name to the listbox with update button
columns = new string[] { "FRMCODE", "FRMNAME" };
data = db.getData(SFADatabase.TABLE_FIRM, columns, "WHERE UGRREF=" + group_id + "");
// firmlistbox.Items.Clear();
firmcodelist.Clear();
firmnamelist.Clear();
for (int i = 0; i < SFADatabase.row_count; i++)
{
ListEditItem item = new ListEditItem(data[i * 2] + " " + data[i * 2 + 1], data[i * 2]);
firmlistbox.Items.Insert(i, item);
firmcodelist.Add(data[i * 2]);
firmnamelist.Add(data[i * 2 + 1]);
}
}
I have attached a gif to be more clear.
enter image description here

No value is present in hidden field after page load

In the below code i have coded in page load.In this i have store regular expressions in hidRegExp.Value. Now i have to store this value in the hidden field.Now in javascript i have to validate the user input in textbox.But when i enter a value it shows blank alert.But i want to display the regular expression in alert.Pls help me to do this.
code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (FieldTypeInfo == FieldType.TextBox)
{
TblSearch.Visible = false;
TblDate.Visible = false;
tblDropd.Visible = false;
TblChk.Visible = false;
lblText.Text = FieldLabel;
//txtreq.Enabled = this.IsMandatory;
string strRegularExp = string.Empty;
if (ListOfRegularExpression != null)
{
for (int iRow = 0; iRow < ListOfRegularExpression.Count; iRow++)
{
strRegularExp += ListOfRegularExpression[iRow].ToString() + "~~";
hidRegExp.Value = strRegularExp;
if (iRow == ListOfRegularExpression.Count - 1)
{
strRegularExp = strRegularExp.TrimEnd("~~".ToCharArray());
txtField.Attributes.Add("onblur", "javascript:ValidateRegExp('" + txtField.ToString() + "');");
}
}
}
hidRegExp.Value = strRegularExp;
lbl.Text = "The value of the HiddenField control is " + hidRegExp.Value + ".";
}}
code:
<script type="text/javascript">
function ValidateRegExp(txtInput) {
var hiddenValue = document.getElementById("<%=hidRegExp.ClientID%>").value;
alert("hiddenValue" + hiddenValue+".");
var mySplitResult = new Array();
mySplitResult = hiddenValue.split("~~");
for (i = 0; i < mySplitResult.length; i++) {
//document.write("<br /> Array[" + i + " ]= " + mySplitResult[i]);
var re = new RegExp(mySplitResult[i]);
if (txtInput.match(re)) {
alert("Successful match");
} else {
alert("No match");
}
}
}
</script>
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState= "true" >
</asp:HiddenField >
<asp:Label ID="lbl" runat="server"></asp:Label>
Initially ListOfRegularExpression will be null so control will not enter into if (ListOfRegularExpression != null) and HiddenField.Value wont be set.
I have had the problem before. Honestly, I don't remember how I resolved it, but I tried a few things. Here they are:
For displaying the hidden field, add ClientIdMode as static on your hidden field like
<asp:HiddenField ID="hidRegExp" runat="server" EnableViewState="true" ClientIDMode="Static"></asp:HiddenField>
and in the JavaScript, use:
document.getElementById("hidRegExp");
If this does not work, try your approach with these below:
1) Try moving your hidden field before the script.
2) Try making it a label and use that in the JavaScript.
Hope this helps.

How to access gridview cell value with javascript

I have a javascript function that I am trying to validate the inputs of a gridview. My problem is that I cannot get the value of the cell. Here is what I have:
function fcnCheck() {
var grid = document.getElementById("<%= GridViewProducts.ClientID %>");
var cellPivot;
if (grid.rows.length > 0) {
for (i = 1; i < grid.rows.length-1; i++) {
cellPivot = grid.rows[i].cells[0];
cellStatus = grid.rows[i].cells[1];
if (cellPivot == "Yes" and cellStatus == "") {
alert("You must select an answer for all columns if Pivot is yes")
return false;
}
}
}
}
This line does not work: cellPivot = grid.rows[i].cells[0];
Most likely you want (edit)
var theDropdown = grid.rows[i].cells[0].elements[0];
var selIndex = theDropdown.selectedIndex;
cellPivot = theDropdown.options[selIndex].value;
Another possibly easier or more reliable way to do this would be to tag the cells controls you want in some way and select them directly?
http://aspdotnetcodebook.blogspot.com/2010/01/how-to-get-cell-value-of-gridview-using.html#comment-form
Code
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var list = "";
$("#btnGet").click(function() {
$("#<%=GridView1.ClientID %> tr").each(function() {
//Skip first(header) row
if (!this.rowIndex) return;
var age = $(this).find("td:last").html();
list += age + "</br>";
});
$("#listAge").html(list)
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<input type="button" id="btnGet" value="Get Cell Value" />
<div id="listAge">
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Create Object of person class
Person personObject = new Person();
//Assign Person list to GridView
GridView1.DataSource = personObject.GetPersonList();
//Call Bindmethod of GridView
GridView1.DataBind();
}
}
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public List<Person> GetPersonList()
{
//Retrun List of Person
List<Person> list = new List<Person>()
{
new Person{ID=1,Name="Person1",Age=32},
new Person{ID=2,Name="Person2",Age=45},
new Person{ID=3,Name="Person3",Age=43},
new Person{ID=4,Name="Person4",Age=21},
new Person{ID=5,Name="Person5",Age=76},
new Person{ID=6,Name="Person6",Age=54},
};
return list;
}
}
<script language="javascript" type="text/javascript">
function Calculate()
<br/>
{
<br/>
var grid = document.getElementById("<%=GridID.ClientID%>");
<br/>
var sum = 0; <br/>
for (var i = 1; i < grid.rows.length; i++)<br/>
{ <br/>
var Cell = grid.rows[i].getElementsByTagName("input");
<br/>if (!Cell[4].value) {sum += 0; } else { sum += parseFloat(Cell[4].value);} }
<br/>
document.getElementById("<%=TextBox1.ClientID%>").value = sum;
}
<br/>
</script>
------------------------------------------------------------------------
<asp:TemplateField HeaderText="Current payment" >
<ItemTemplate>
<asp:TextBox ID="cridnvalue" runat="server" Width="70px" BorderStyle="None" onkeyup="CalculateTax();" ></asp:TextBox>
</ItemTemplate>
<ItemStyle Width="120px" />
</asp:TemplateField>
//your gridview id in my case my gridview is named dgd and the id comes from
// ClientID
var myGrid = document.getElementById("<%= dgd.ClientID %>");
var oRows = myGrid.rows;
var k;
for (k = 1; k < oRows.length; k++)
{
var currentRow = myGrid.rows[k];
//now you can see the 1st,2nd and 3trd column value
alert(currentRow.cells[1].innerHTML);
alert(currentRow.cells[2].innerHTML);
alert(currentRow.cells[3].innerHTML);
}
function rowWisegetcellvalueingridview() {
///concat string
var str1 = "";
var n = document.getElementById('hdnColumn').value;
///concat string
var grid = document.getElementById('GridView1');
var Inputs = grid.getElementsByTagName('input');
var Inputsa = grid.getElementsByTagName('a');
var Inputsspan = grid.getElementsByTagName('span');
var Input = Inputs.length;
var j = 0;
var p = 0;
var r = 0;
for (t = 0; t < grid.rows.length - 1; t++) {
var HdnID1 = Inputs[j].value;
var HdnID2 = Inputs[j + 1].value;
var HdnID3 = Inputs[j + 2].value;
var HdnID4 = Inputs[j + 3].value;
var HdnID5 = Inputsa[p].innerHTML;
var HdnID6 = Inputsa[p + 1].innerHTML;
var HdnID7 = Inputsspan[r].innerHTML;
var varConcat = "(" + HdnID1 + "," + HdnID2 + "," + HdnID3 + "," + HdnID4 + "," + HdnID5 + "," + HdnID6 + "," + HdnID7 + "),\n";
n = n.concat(varConcat);
j = j + 4;
p = p + 2;
r = r + 1;
}
return false;
}

Categories

Resources