Forgive my English, I had one challenge in my project I,e whenever I started to access hidden field value which in grid view using JavaScript or Jquery, I'm getting compilation error like hidden field doesn't exist in current context so how can I access hidden field value?
SelectPatientInfo.aspx
<asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="Server">
<script type="text/javascript">
function DispValue(sender, e) {
var id = e.get_value();
document.getElementById("<%=PatientRefferalId.ClientID%>").value=id; //getting error here
}
</script>
<div align="left" style="float: left; margin-left: 5px;">
<asp:GridView ID="gvPatient" runat="server" AutoGenerateColumns="false" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="12px" HeaderStyle-Height="20px">
<HeaderTemplate> Patient Name </HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="PatientRefferalId" runat="server" Value="0" />
<PUC:PatientUserControl ID="pucPatient1" runat="server" OnClientSelect="DispValue" PTStatusShow="0"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>
SelectPatientInfo.aspx.cs
protected void Page_Load(object sender, EventArgs e) {
try {
if (!IsPostBack) {
dt = new DataTable();
dt.Columns.Add("col1");
dt.Columns.Add("col2");
dt = AddRow(dt);
gvPatient.DataSource = dt;
gvPatient.DataBind();
}
} catch (Exception ex) {
}
}
private DataTable AddRow(DataTable dt) {
for (int i = 0; i < 5; i++) {
DataRow dr = dt.NewRow();
dr[0] = "";
dr[1] = ""; dt.Rows.Add(dr);
}
return dt;
}
protected void GridPatient_DataBound(object sender, EventArgs e) {
try {
foreach (GridViewRow item in gvPatient.Rows) {
HiddenField hfReferralId = (HiddenField)item.FindControl("PatientRefferalId");
Response.write(hfReferralId.Value);
}
} catch (Exception ex) {
}
}
I'm not sure the code
document.getElementById("<%=PatientRefferalId.ClientID%>")
will work, because you don't have only one "PatientRefferalId", but you get many (as many as numbers of rows in your gridview).
I don't know if there is a cleaner way, but I can do what you want by using this javascript code
var gv = document.getElementById("<%=gvPatient.ClientID%>");
var Rows = gv.getElementsByTagName("tr"); // Get all the rows from your gridview (rendered as html table).
// you can loop through the rows or if you know the row index, you can do:
alert(Rows[2].childNodes[0].children[0].value); // Show you the first control (the hiddenfield) of the first cell of the row #2.
Hi This post may help you.
var c = document.getElementsByTagName("table");
for (var i = 0; i < c.length; i++) {
if (c[i].id.indexOf("GridView1") > -1) {
var hidd = c[i].getElementsByTagName("input");
for (var j = 0; j < hidd.length; j++) {
if (hidd[j].type == "hidden")
alert(hidd[j].id);
}
}
}
And also refer following link .. its working to me..
http://forums.asp.net/p/1510265/3603566.aspx/1?Re+how+to+find+gridview+hidden+label+value+from+javascript
<asp:Content ID="Content2" ContentPlaceHolderID="cphContent" runat="Server">
<script type="text/javascript">
function DispValue(btnShow) {
var parentRow = $(btnShow).closest("tr");
var hiddenField=parentRow.find('input[id$=PatientRefferalId]');
alert(hiddenField.val());
return false;
}
</script>
<div align="left" style="float: left; margin-left: 5px;">
<asp:GridView ID="gvPatient" runat="server" AutoGenerateColumns="false" EnableViewState="true">
<Columns>
<asp:TemplateField HeaderStyle-Font-Bold="true" HeaderStyle-Font-Size="12px" HeaderStyle-Height="20px">
<HeaderTemplate> Patient Name </HeaderTemplate>
<ItemTemplate>
<asp:HiddenField ID="PatientRefferalId" runat="server" Value="0" />
<asp:LinkButton ID="lnkPopUp" runat="server" Style="font-size: 16px;" OnClientClick="return DispValue(this)" Text="PopUp"
></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</asp:Content>
Related
I daynamically create options of select in javascript, and click a asp:Button to submit the added options. but i can't get that from ListBox. pls help me!!
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Hello.aspx.cs" Inherits="BeyondInfo.Hello" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Welcome to My First ASP.NET</title>
<script type="text/javascript">
function add() {
var count = document.getElementById("count");
if (count.value == "") {
count.value = 1;
}
count.value = parseInt(count.value) + 1;
var num = count.value;
var listBox2 = document.getElementById("ListBox2");
var optn = document.createElement("OPTION");
optn.value = num;
optn.text = num + "_add";
listBox2.options.add(optn);
}
</script>
</head>
<link href="Common.css" rel="stylesheet" />
<body>
<form id="form1" runat="server">
<div style="height: 277px">
<asp:ListBox ID="ListBox2" runat="server">
<asp:ListItem>b1222222222222222222222222222</asp:ListItem>
<asp:ListItem>b2</asp:ListItem>
<asp:ListItem>b3</asp:ListItem>
<asp:ListItem>b4</asp:ListItem>
</asp:ListBox>
<input id="count" type="hidden" />
<input id="btnAdd" type="button" value="ADD" onclick="add()"/>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" />
</form>
</body>
</html>
</p>
Hello.aspx.cs
public partial class Hello : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
string sel = "";
foreach (ListItem item in ListBox2.Items) {
sel +=item.Text + ",";
}
Label1.Text = sel;
}
}
Try looking at this post answer by NC01. You may be able to achieve what you want by doing something similar.
Basically they store the added fields in a hidden field so they are accessible server side.
I believe that your problem is that when you add an item to a DropDownList client-side (using JavaScript) that when a PostBack occurs, the item will disappear. The only way around this is to add a hidden server-control to the page and when adding the item client-side, add it to the hidden server-control also, so that when a PostBack occurs you can also add it server-side.
Here's an example.
https://forums.asp.net/t/1287204.aspx?How+to+add+the+values+to+listbox+control+using+javascript
aspx file:
<form id="Form1" method="post" runat="server">
<asp:DropDownList id="DropDownList1" runat="server">
<asp:listitem value="1">Item 1</asp:listitem>
<asp:listitem value="2">Item 2</asp:listitem>
<asp:listitem value="3">Item 3</asp:listitem>
<asp:listitem value="4">Item 4</asp:listitem>
<asp:listitem value="5">Item 5</asp:listitem>
<asp:listitem value="6">Item 6</asp:listitem>
</asp:DropDownList>
<input id="DropDownList1NewItems" type="hidden" name="DropDownList1NewItems" runat="server">
<input type="button" onclick="addItem();" value="Add Item">
</form>
<script type="text/javascript">
<!--
function addItem()
{
// Add the item here...
var ddlRef = document.getElementById('<%= DropDownList1.ClientID %>');
var newOption = window.document.createElement('OPTION');
newOption.text = 'SomeNewItem';
newOption.value = 'SomeNewItem';
ddlRef.options.add(newOption);
var hiddenElementRef = document.getElementById('<%= DropDownList1NewItems.ClientID %>');
if ( hiddenElementRef.value.length > 0 )
hiddenElementRef.value += ';';
hiddenElementRef.value += 'SomeNewItem';
}
// -->
</script>
aspx.cs file:
private void Page_Load(object sender, System.EventArgs e)
{
if ( this.IsPostBack )
{
if ( DropDownList1NewItems.Value.Length > 0 )
{
string [] newItemsArray = DropDownList1NewItems.Value.Split(';');
for (int i=0; i<newItemsArray.Length; i++)
{
string newItem = newItemsArray[i];
DropDownList1.Items.Add(new ListItem(newItem, newItem));
}
DropDownList1NewItems.Value = string.Empty;
}
}
}
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";
}
}
I am trying to create a file upload control dynamically for updating word documents. I have the following code in my aspx page.
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" DataKeyNames="FilePath" EmptyDataText="No documents attached" >
<HeaderStyle BackColor="Purple" Font-Bold="true" ForeColor="White" />
<Columns>
<asp:TemplateField HeaderText="FilePath">
<ItemTemplate>
<asp:LinkButton ID="lnkDownload" runat="server" Text="My Document" OnClick="lbDownloadDocument_Click"></asp:LinkButton>
<img src="Image/delete.jpg" alt="" onclick="AddFile()" /><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Update" OnClick="Button2_Click" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have the following code in my .cs page.
protected void Button2_Click(object sender, EventArgs e)
{
for (int i = 0; i < Request.Files.Count; i++)
{
HttpPostedFile PostedFile = Request.Files[i];
if (PostedFile.ContentLength > 0)
{
string FileName = System.IO.Path.GetFileName(PostedFile.FileName);
PostedFile.SaveAs(Server.MapPath("~/Files/") + FileName);
}
}
}
And my script is :
<script type="text/javascript">
var i = 1;
function AddFile() {
i++;
var div = document.createElement('DIV');
div.innerHTML = '<input id="file' + i + '" name = "file' + i + '" type="file" /><img src="~/Image/delete.jpg" alt="Remove" onclick = "RemoveFile(this)" />';
document.getElementById("divFile").appendChild(div);
}
function RemoveFile(file) {
document.getElementById("divFile").removeChild(file.parentNode);
}
</script>
But Somehow this code is not working. I don't have much idea of file upload control. Please help me with it. Should I use an Update panel ?
I have issue to disable/enable validators for newly add row to gridview which is in Update panel, If I remove Update panel then it's worked perfect, and If I add Update panel then it stops working. I have created sample page.
Default.aspx.
<head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $('table > tbody > tr .wrapper [class*="onoff"] option:selected').each(function (index) { adjustValidators(this); }); $('[class*="onoff"] select').change(function () { adjustValidators($('option:selected', this)[0]); }); }); </script></head>
<ajax:ToolkitScriptManager runat="server" ID="RadScriptManager1" AsyncPostBackTimeout="18000"> </ajax:ToolkitScriptManager><asp:MultiView ID="MultiView1" runat="server"> <asp:View ID="group_Group1" runat="server"> <div class="group group1"> <asp:Button ID="btnNext0_top" runat="server" Text="Next >>" OnClick="btnNext_Click" ValidationGroup="surveyValidate0" /> <asp:UpdatePanel runat="server" ID="UPNew" UpdateMode="Conditional"> <ContentTemplate> <asp:GridView runat="server" ID="repeatregion_RRSectionSS" RegionName="RRSectionSS" AutoGenerateColumns="False" GridLines="None" CellSpacing="-1" CssClass="rrsectionss"> <Columns> <asp:TemplateField> <ItemTemplate> <div id="wrapper_ONOFF" runat="server" class="wrapper onoff"> <div class='statement onoff' id="statement_ONOFF" runat="server"> Required Validator :</div> <div class='question onoff' id="questionlayer_ONOFF" runat="server"> <asp:DropDownList runat="server" ID="question_ONOFF" ValidationGroup="surveyValidate0" Data='<%# Eval("ONOFF") %>' Val='<%# Eval("ONOFF_selectedValue") %>'> <asp:ListItem Text="Off" Value="-1"></asp:ListItem> <asp:ListItem Value="1" Text="On"></asp:ListItem> </asp:DropDownList> </div> </div> <div id="wrapper_testsssss" runat="server" class="wrapper testsssss"> <div class='statement testsssss' id="statement_testsssss" runat="server"> Sample Text </div> <div class='question testsssss' id="questionlayer_testsssss" runat="server"> <asp:TextBox runat="server" ID="question_testsssss" type="shortans" Columns='40' ValidationGroup="surveyValidate0" Text='<%# Common.DecodeXML(Eval("testsssss")) %>'></asp:TextBox> <asp:RequiredFieldValidator ID="rfv_question_testsssss" runat="server" ValidationGroup="surveyValidate0" SetFocusOnError="true" EnableClientScript="true" ControlToValidate="question_testsssss" Display="Dynamic" Text="**" ErrorMessage="**" /> </div> </div> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button runat="server" ID="btnAddClick" Text="Add Section" OnClick="btn_Click" /> </ContentTemplate> </asp:UpdatePanel> </div> </asp:View> <asp:View ID="group_Group2" runat="server"> <div class="group group2"> <asp:Button ID="btnPrevious1_top" runat="server" Text="<< Prev" OnClick="btnPrevious_Click" /> <asp:Button ID="btnSubmit" runat="server" Text="Submit" ValidationGroup="surveyValidate1" /> </div> </asp:View> </asp:MultiView>
<script type="text/javascript"> function pageLoad(sender, args) { if (args.get_isPartialLoad()) { $('table > tbody > tr .wrapper [class*="onoff"] option:selected').each(function (index) { adjustValidators(this); }); } } function adjustValidators(ctrl) { var id = ctrl.parentNode.id.replace('_question', '_rfv_question').replace('ONOFF', 'testsssss') // alert(ctrl.value); if (ctrl.value == -1) { ValidatorEnable(eval(id), false) } else { ValidatorEnable(eval(id), true) } } </script>
Default.aspx.cs.
protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = (MultiView1.ActiveViewIndex == -1) ? 0 : MultiView1.ActiveViewIndex;
DataTable objData =new DataTable();
if (ViewState["data"] != null)
{
objData = (DataTable)ViewState["data"];
}
else
{
objData = new DataTable();
objData.Columns.Add("testsssss");
objData.Columns.Add("ONOFF");
objData.Columns.Add("ONOFF_selectedValue");
objData.Rows.Add(objData.NewRow());
ViewState["data"] = objData;
}
if (!IsPostBack)
{
repeatregion_RRSectionSS.DataSource = objData;
repeatregion_RRSectionSS.DataBind();
}
}
protected void btnNext_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex += 1;
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex -= 1;
}
protected void btn_Click(object sender, EventArgs e)
{
DataTable objData = (DataTable)ViewState["data"];
objData.Rows.Add(objData.NewRow());
repeatregion_RRSectionSS.DataSource = objData;
repeatregion_RRSectionSS.DataBind();
ViewState["data"] = objData;
}
when Click on add then item get added to gridview but validators are not disabled.
Thanks and Regards
Sadiq Modan
After some research and trickery I found the solution: replace eval in ValidatorEnable(eval(id), false) with document.getElementById(id). It worked for me.
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`