Ajax Timer: Execute only 5 times - c#

I have a ajax Timer control. It adds “+” to the text value of a label. This timer should work only five times with an interval of “1000” – i.e, only five “+” should be available. After that, the lblPostbackType
Should be updated with the count. How do I achieve it?
public partial class _Default : System.Web.UI.Page
{
static int partialPostBackCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
partialPostBackCount = partialPostBackCount + 1;
lblPostbackType.Text = "Partial Postback:: " + partialPostBackCount.ToString();
}
else
{
lblPostbackType.Text = "Full Postback";
}
}
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Label1.Text = Label1.Text + "+";
}
}
And the designer code is
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" ID="Timer1" Interval="1000" OnTick="Timer1_Tick" />
<asp:Label runat="server" ID="lblPostbackType" >SAMPLE</asp:Label>
<asp:UpdatePanel runat="server" ID="TimePanel" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" ID="Label1" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
Thanks

try this
protected void Timer1_Tick(object sender, EventArgs e)
{
if (partialPostBackCount > 5 )
{
lblPostbackType.Text = "Partial Postback:: " +
partialPostBackCount.ToString();
//Timer1.Enabled = false; //if you don't want it to continue
}
else
{
partialPostBackCount = partialPostBackCount + 1;
Label1.Text = Label1.Text + "+";
}
}
*static variables are not recommended..
keep the Page_Load event method clean..

Related

Dynamic TextBox TextChanged is not firing in UpdatePanel

My dynamic textboxes TextChanged event is working properly without using UpdatePanel, but when i use UpdatePanel it stops working. it works only when Button is clicked and when the LinkButton is clicked.
How can i set TextChanged event of dynamic textboxes as trigger for the UpdatePanel. I hope this is clear for you.
This is my aspx
<form id="form1" runat="server" enctype="multipart/form-data">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Name :"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label2" runat="server" Text="Age :"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<br />
<asp:Label ID="Label3" runat="server" Text="Phones :"></asp:Label>
<br />
<asp:Panel ID="pnlTextBox" runat="server">
</asp:Panel>
<asp:LinkButton ID="btnAddTxt" runat="server" OnClick="btnAddTxt_Click">Add TextBox</asp:LinkButton>
<br />
<br />
<asp:Button ID="Button1" runat="server" Text="save" OnClick="Button1_Click" />
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="Button1" />
</Triggers>
</asp:UpdatePanel>
</form>
and this is code behind
protected void Page_PreInit(object sender, EventArgs e)
{
//Recreate Controls
RecreateControls("txtDynamic", "TextBox");
}
protected void btnAddTxt_Click(object sender, EventArgs e)
{
int cnt = FindOccurence("txtDynamic");
CreateTextBox("txtDynamic-" + Convert.ToString(cnt + 1));
}
private int FindOccurence(string substr)
{
string reqstr = Request.Form.ToString();
return ((reqstr.Length - reqstr.Replace(substr, "").Length) / substr.Length);
}
private void RecreateControls(string ctrlPrefix, string ctrlType)
{
string[] ctrls = Request.Form.ToString().Split('&');
int cnt = FindOccurence(ctrlPrefix);
if (cnt > 0)
{
for (int k = 1; k <= cnt; k++)
{
for (int i = 0; i < ctrls.Length; i++)
{
if (ctrls[i].Contains(ctrlPrefix + "-" + k.ToString()) && !ctrls[i].Contains("EVENTTARGET"))
{
string ctrlID = ctrls[i].Split('=')[0];
if (ctrlType == "TextBox")
{
CreateTextBox(ctrlID);
}
break;
}
}
}
}
}
private void CreateTextBox(string ID)
{
TextBox txt = new TextBox();
txt.ID = ID;
txt.AutoPostBack = true;
txt.TextChanged += new EventHandler(OnTextChanged);
pnlTextBox.Controls.Add(txt);
Literal lt = new Literal();
lt.Text = "<br /><br />";
pnlTextBox.Controls.Add(lt);
}
protected void OnTextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox)sender;
string ID = txt.ID;
//Place the functionality here
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('" + ID + " fired OnTextChanged event')", true);
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox txtDynamic1 = (TextBox)this.form1.FindControl("txtDynamic-1");
TextBox txtDynamic2 = (TextBox)this.form1.FindControl("txtDynamic-2");
Response.Write(txtDynamic1.Text + " & " + txtDynamic2.Text);
}
You can refer to this URL and add the postback trigger from the code behind instead of the aspx. https://forums.asp.net/t/1124967.aspx?Adding+a+Trigger+to+an+UpdatePanel+in+code+behind

Limit consecutive numbers entered into textbox [Calculator App]

I am building a calculator app (it is homework, full disclosure) and have got myself into a bit of a jam. One of the requirements is "make sure that you will not be able to enter more than 9 digits. (i.e., < 1,000,000,000)".
What I'd really like to do is cap off an entered number to 9 digits and make exceptions for operators (+ - * /)
Things I've tried>
Using RegularExpressionValidator and while I am able to use that to limit the text but it is less than ideal.
Creating an integer to use as a counter in the code-behind, and have each input that is a digit increase the counter by 1 and each operator reset it to 0. Then, when any digit key is pressed, have it check to see if the Counter >=9 and have it display an alert if so. That was what I was really hoping would work but I had no luck.
My solve method requires that the entire expression (including operators) be in the CurrentInput textbox. If I'm not able to figure this out, I'm going to have to scrap what I'm doing and do it another way. That'd be unfortunate, because I've also built an identical calculator using Javascript and I'd have to re-do that as well. My goof was not thinking through the intended behavior of the calculator before I got this far. From the requirements (linked below), it seems the display boxes only show numbers and keep the current operator in a separate box. I have the current operator displayed as well to the right of the "9" key but also in the display box.
Requirements
This is my design, and i've pasted screenshots next to each other to demonstrate its behavior in one continuous operation. 450 divided by 150 = 3 then if an operator is the next entered input, it continues to modify the result so: * 200 + 550 = 1150. If a digit is the next entered input, it sends the result to the top display so: 5 * 5 = 25. I don't really know exactly how a dual display calculator is supposed to work but that's the best I can figure.
Design&Behavior
This is my ASP.Net code:
<body>
<form id="CAsp" runat="server">
<div>
<asp:Table ID="Table1" runat="server">
<asp:TableHeaderRow runat="server">
<asp:TableHeaderCell CssClass="th" ColumnSpan="4" runat="server" Enabled="false">
<asp:TextBox ID="Result" runat="server"></asp:TextBox>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableHeaderRow runat="server">
<asp:TableHeaderCell CssClass="th" ColumnSpan="4" runat="server" Enabled="false">
<asp:TextBox ID="CurrentInput" runat="server"></asp:TextBox>
</asp:TableHeaderCell>
</asp:TableHeaderRow>
<asp:TableRow CssClass="toprow" runat="server">
<asp:TableCell CssClass="topleft" runat="server">
<asp:Button ID="Seven" CssClass="smallbutton" runat="server" OnClick="Seven_OnClick" Text="7" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Eight" CssClass="smallbutton" runat="server" OnClick="Eight_OnClick" Text="8" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Nine" CssClass="smallbutton" runat="server" OnClick="Nine_OnClick" Text="9" /></asp:TableCell>
<asp:TableCell CssClass="topright" runat="server">
<asp:Button ID="OP" CssClass="OP" runat="server" Enabled="false" Text="" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Button ID="Four" CssClass="smallbutton" runat="server" OnClick="Four_OnClick" Text="4" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Five" CssClass="smallbutton" runat="server" OnClick="Five_OnClick" Text="5" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Six" CssClass="smallbutton" runat="server" OnClick="Six_OnClick" Text="6" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Clear" CssClass="smallbutton" runat="server" OnClick="Clear_OnClick" Text="C" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Button ID="One" CssClass="smallbutton" runat="server" OnClick="One_OnClick" Text="1" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Two" CssClass="smallbutton" runat="server" OnClick="Two_OnClick" Text="2" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Three" CssClass="smallbutton" runat="server" OnClick="Three_OnClick" Text="3" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Divide" CssClass="smallbutton" runat="server" OnClick="Divide_OnClick" Text="/" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Button ID="Zero" CssClass="smallbutton" runat="server" OnClick="Zero_OnClick" Text="0" /></asp:TableCell>
<asp:TableCell CssClass="topright" runat="server">
<asp:Button ID="Plus" CssClass="smallbutton" runat="server" OnClick="Plus_OnClick" Text="+" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Minus" CssClass="smallbutton" runat="server" OnClick="Minus_OnClick" Text="-" /></asp:TableCell>
<asp:TableCell runat="server">
<asp:Button ID="Multiply" CssClass="smallbutton" runat="server" OnClick="Multiply_OnClick" Text="*" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow CssClass="bottomrow" runat="server">
<asp:TableCell CssClass="bottomcell" ColumnSpan="4" runat="server">
<asp:Button ID="Equals" CssClass="longbutton" runat="server" OnClick="Equals_OnClick" Text="=" /></asp:TableCell>
</asp:TableRow>
</asp:Table>
<div align="center">
<asp:RegularExpressionValidator ID="REV1" runat="server" ForeColor="red" ErrorMessage="Max Characters is 9, Use Backspace" ControlToValidate="CurrentInput" Display="Dynamic" ValidationExpression="^[0-9+-/*\s]{0,9}$" /></div>
</div>
</form>
And this is my C# code-behind:
public partial class CalcAsp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void Equals_OnClick(object sender, EventArgs e)
{
try
{
string Input = CurrentInput.Text;
DataTable datatable = new DataTable();
Object result;
result = datatable.Compute(Input, null);
CurrentInput.Text = result.ToString();
OP.Text = "=";
}
catch
{
CurrentInput.Text = "Error";
}
}
protected void Clear_OnClick(object sender, EventArgs e)
{
CurrentInput.Text = "";
Result.Text = "";
OP.Text = "";
}
protected void Plus_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "+";
OP.Text = "+";
}
}
protected void Minus_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "-";
OP.Text = "-";
}
}
protected void Multiply_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "*";
OP.Text = "*";
}
}
protected void Divide_OnClick(object sender, EventArgs e)
{
if (CurrentInput.Text == "")
{
ScriptManager.RegisterStartupScript(this, GetType(), "alertMessage", "alert('Enter A Digit!');", true);
}
else
{
CurrentInput.Text = CurrentInput.Text + "/";
OP.Text = "/";
}
}
public void Zero_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "0";
}
else
{
CurrentInput.Text = CurrentInput.Text + "0";
}
}
public void One_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "1";
}
else
{
CurrentInput.Text = CurrentInput.Text + "1";
}
}
public void Two_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "2";
}
else
{
CurrentInput.Text = CurrentInput.Text + "2";
}
}
protected void Three_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "3";
}
else
{
CurrentInput.Text = CurrentInput.Text + "3";
}
}
protected void Four_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "4";
}
else
{
CurrentInput.Text = CurrentInput.Text + "4";
}
}
protected void Five_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "5";
}
else
{
CurrentInput.Text = CurrentInput.Text + "5";
}
}
protected void Six_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "6";
}
else
{
CurrentInput.Text = CurrentInput.Text + "6";
}
}
protected void Seven_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "7";
}
else
{
CurrentInput.Text = CurrentInput.Text + "7";
}
}
protected void Eight_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "8";
}
else
{
CurrentInput.Text = CurrentInput.Text + "8";
}
}
protected void Nine_OnClick(object sender, EventArgs e)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = "9";
}
else
{
CurrentInput.Text = CurrentInput.Text + "9";
}
}
protected void backSpace_Click(object sender, EventArgs e)
{
String str = CurrentInput.Text;
int len;
len = str.Length;
CurrentInput.Text = "";
for (int i = 0; i < len - 1; i++)
{
CurrentInput.Text = CurrentInput.Text + Convert.ToString(str[i]);
}
}
}
Thanks for any pointers. I've been reading stackoverflow for years so I think I'm coming in within the community norms on this question, but it is my first post. :)
You can use MaskedEdit Validator from AjaxControlToolkit. It sets pre-defined format for your textbox and prevents user from entering anything other than that. I used this control in one of my project and it works like a charm. The behaviour of the control is rendered in javascript at runtime and it makes a smooth user experience without any postback to server.
For more details - http://www.ajaxcontroltoolkit.com/MaskedEdit/MaskedEdit.aspx
Let me know if you need further help.
First, I would create a method to handle the number clicks. Then alter your insertion code to include a counter of some sort. Something like this might work:
protected void InsertNumber(int number)
{
int numberCount = 0;
for (int i = 0; i < CurrentInput.Text.Length; i++)
{
try
{
if (Enumberable.Range(0, 9).Contains(Convert.ToInt32(CurrentInput.Text.Substring(i, 1))))
{
numberCount++;
}
}
catch
{
// Do nothing?
}
}
if (numberCount <= 9)
{
if (OP.Text == "=")
{
Result.Text = CurrentInput.Text;
CurrentInput.Text = number.ToString();
}
else
{
CurrentInput.Text += number.ToString();
}
}
}
// Exacmple usage, apply to all buttons
protected void Nine_OnClick(object sender, EventArgs e)
{
InsertNumber(9);
}
I cannot test at the moment, but it should work.

Updating ASP.NET UpdatePanel during processing loop

I've seen this particular problem posted multiple times but none of the solutions I've seen actually accomplish what I'm trying to do.
I have an ASP.NET page with an UpdatePanel on it. In the UpdatePanel is a button and a multiline textbox. The button's click event disables the button and enters a processing loop that updates the Text property of the TextBox multiple times. But, of course, the TextBox is not actually updated until the loop completes.
I've seen suggestions to add a Timer control to the page and I've tried that. But the Timer's Tick doesn't fire during until the loop is complete so it's no use!
Does ANYONE have a working solution for this? I need a page that allows the user to click a button to initiate a process that processes multiple records in a database and gives updates to the user indicating each record processed.
Here's my page code:
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="230px" TextMode="MultiLine"
Width="800px"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Here's my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace UpdatePanel
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Enabled = false;
for (int x = 1; x < 6; x++)
{
ViewState["progress"] += "Beginning Processing Step " + x.ToString() + " at " + DateTime.Now.ToLongTimeString() + "..." + System.Environment.NewLine;
System.Threading.Thread.Sleep(1000); //to simulate a process that takes 1 second to complete.
ViewState["progress"] += "Completed Processing Step " + x.ToString() + " at " + DateTime.Now.ToLongTimeString() + System.Environment.NewLine;
TextBox1.Text = ViewState["progress"].ToString();
}
}
}
}
If I simply set the VewState value in the loop and then add a Timer that sets the TextBox Text property to the ViewState value, that code never fires until the loop is completed.
Well, I finally found the answer in this post. I've adjusted my own code accordingly (with a few tweaks) and it works perfectly now.
Here's my page code:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="UpdatePanel.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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Timer runat="server" ID="Timer1" Interval="1000" Enabled="false" ontick="Timer1_Tick" />
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
<ContentTemplate>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
<br />
<asp:TextBox ID="TextBox1" runat="server" Height="250px" TextMode="MultiLine"
Width="800px"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>
Here's my code-behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;
namespace UpdatePanel
{
public partial class Default : System.Web.UI.Page
{
protected static string content;
protected static bool inProcess = false;
protected static bool processComplete = false;
protected static string processCompleteMsg = "Finished Processing All Records.";
protected void Page_Load(object sender, EventArgs e){ }
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Enabled = false;
Timer1.Enabled = true;
Thread workerThread = new Thread(new ThreadStart(ProcessRecords));
workerThread.Start();
}
protected void ProcessRecords()
{
inProcess = true;
for (int x = 1; x <= 5; x++)
{
content += "Beginning Processing Step " + x.ToString() + " at " + DateTime.Now.ToLongTimeString() + "..." + System.Environment.NewLine;
Thread.Sleep(1000);
content += "Completed Processing Step " + x.ToString() + " at " + DateTime.Now.ToLongTimeString() + System.Environment.NewLine + System.Environment.NewLine;
}
processComplete = true;
content += processCompleteMsg;
}
protected void Timer1_Tick(object sender, EventArgs e)
{
if (inProcess)
TextBox1.Text = content;
int msgLen = processCompleteMsg.Length;
if (processComplete && TextBox1.Text.Substring(TextBox1.Text.Length - processCompleteMsg.Length) == processCompleteMsg) //has final message been set?
{
inProcess = false;
Timer1.Enabled = false;
Button1.Enabled = true;
}
}
}
}
Are you looking for this
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Enabled = false;
for (int x = 1; x < 6; x++)
{
ViewState["progress"] += "Beginning Processing Step " + x.ToString() + " at " + DateTime.Now.ToLongTimeString() + "..." + System.Environment.NewLine;
System.Threading.Thread.Sleep(1000); //to simulate a process that takes 1 second to complete.
ViewState["progress"] += "Completed Processing Step " + x.ToString() + " at " + DateTime.Now.ToLongTimeString() + System.Environment.NewLine;
TextBox1.Text += ViewState["progress"].ToString();
}
}

How Can I retrieve data from TextBox, when it's dynamically added by button?

I'm new to coding, hope some can help me a bit, I got stuck at retrieving data from my Dynamically added Text boxes in ASP.NET.
I Master Site and a Content site. I have added some buttons to the content site there are adding or removing the textboxes, after what's needed by the user.
My problem is, that i'm not sure how to retrieve the data correct. hope some body can help me on the way.
My Content site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Her Kan de oprette alt det udstyr der skal sendes til reperation hos zenitel.
</p>
</div>
<div id="div_insert_devices" runat="server">
</div>
// 3 buttons one who add, one who remove textboxes and a submit button
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ViewState["DeviceCount"] = ViewState["DeviceCount"] == null ? 1 : ViewState["DeviceCount"];
InsertLine();
}
}
private void InsertLine()
{
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
LiteralControl text = new LiteralControl("<div class=\"divPerDevice\">");
div_insert_devices.Controls.Add(text);
TextBox txtbox = new TextBox();
txtbox.ID = "serial" + i;
txtbox.CssClass = "textbox1";
txtbox.Attributes.Add("runat", "Server");
div_insert_devices.Controls.Add(txtbox);
text = new LiteralControl("</div>");
div_insert_devices.Controls.Add(text);
}
}
protected void btnAddRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count++;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnRemoveRow_Click(object sender, EventArgs e)
{
int count = int.Parse(ViewState["DeviceCount"].ToString());
count--;
ViewState["DeviceCount"] = count;
InsertLine();
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
}
}
((TextBox)div_insert_devices.FindControl("txtboxname")).Text
Try this one
you can use the following code
protected void btnSubmit_Click(object sender, EventArgs e)
{
// Submit - save the textboxes to Strings ??? Can any body help
int DeviceCount = int.Parse(ViewState["DeviceCount"].ToString());
for (int i = 0; i < DeviceCount; i++)
{
TextBox txtbx= (TextBox)div_insert_devices.FindControl("serial" + i);
if(txtbx!=null)
{
var value= txtbx.Text;
}
}
}
The way i would attempt this is like the following:
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (Control control in div_insert_devices.Controls){
if (control.GetType() == typeof(textbox)){
Textbox myDynTextbox = (Textbox)control;
Var myString = myDynTextbox.Text;
Please note this code can be simplyfied further but, i have written it this was so you understand how it would work, and my advise would be to store all the strings in a collection of Strings, making it easier to maintain.
}
}
}
Kush
Why don't you use javascript to save the value of textbox. just hold the value in some hidden field and bind it everytime when you need it.
Hi I found the solution after some time here... I did not got any of examples to work that you have provided. sorry.
But I almost started from scratch and got this to work precis as I wanted :)
My Content Site:
<%# Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="CreateRMA.aspx.cs" Inherits="CreateRMA" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="mainsite" Runat="Server">
<div id="div_fortext" class="div_fortext">
<p class="header2">
Opret RMA Sag
</p>
<p class="text1">
Some TEXT
</p>
</div>
</div>
<asp:Button ID="btnAddRow" runat="server" Text="Add Row" CssClass="butten1" OnClick="btnAddRow_Click" />
<asp:Button ID="btnRemoveRow" runat="server" Text="Remove Row" CssClass="butten1" OnClick="btnRemoveRow_Click" />
<asp:Button ID="btnSubmit" runat="server" Text="Submit" CssClass="butten1" OnClick="btnSubmit_Click" />--%>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:PlaceHolder runat="server" id="DynamicDevices"></asp:PlaceHolder>
<asp:Button id="btnAddTextBox" runat="server" text="Tilføj" CssClass="butten1" OnClick="btnAddTextBox_Click" />
<asp:Button id="btnRemoveTextBox" runat="server" text="Fjern" CssClass="butten1" OnClick="btnRemoveTextBox_Click" />
<asp:Button runat="server" id="Submit" text="Submit" CssClass="butten1" OnClick="Submit_Click" />
<br /><asp:Label runat="server" id="MyLabel"></asp:Label>
</asp:Content>
My C# code behind:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class CreateRMA : System.Web.UI.Page
{
static int myCount = 1;
private TextBox[] dynamicTextBoxes;
private TextBox[] Serial_arr;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
myCount = 1;
}
}
protected void Page_Init(object sender, EventArgs e)
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAddTextBox")
{
myCount = myCount >= 30 ? 30 : myCount + 1;
}
if (myControl.ID.ToString() == "btnRemoveTextBox")
{
myCount = myCount <= 1 ? 1 : myCount - 1;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
dynamicTextBoxes = new TextBox[myCount];
Serial_arr = new TextBox[myCount];
int i;
for (i = 0; i < myCount; i += 1)
{
LiteralControl literalBreak = new LiteralControl("<div>");
DynamicDevices.Controls.Add(literalBreak);
TextBox Serial = new TextBox();
Serial.ID = "txtSerial" + i.ToString();
Serial.CssClass = "";
DynamicDevices.Controls.Add(Serial);
Serial_arr[i] = Serial;
TextBox textBox = new TextBox();
textBox.ID = "myTextBox" + i.ToString();
DynamicDevices.Controls.Add(textBox);
dynamicTextBoxes[i] = textBox;
literalBreak = new LiteralControl("</div>");
DynamicDevices.Controls.Add(literalBreak);
}
}
public static Control GetPostBackControl(Page thePage)
{
Control mycontrol = null;
string ctrlname = thePage.Request.Params.Get("_EVENTTARGET");
if (((ctrlname != null) & (ctrlname != string.Empty)))
{
mycontrol = thePage.FindControl(ctrlname);
}
else
{
foreach (string item in thePage.Request.Form)
{
Control c = thePage.FindControl(item);
if (((c) is System.Web.UI.WebControls.Button))
{
mycontrol = c;
}
}
}
return mycontrol;
}
protected void Submit_Click(object sender, EventArgs e)
{
int deviceCount = Serial_arr.Count();
DataSet ds = new DataSet();
ds.Tables.Add("Devices");
ds.Tables["Devices"].Columns.Add("Serial", System.Type.GetType("System.String"));
ds.Tables["Devices"].Columns.Add("text", System.Type.GetType("System.String"));
for (int x = 0; x < deviceCount; x++)
{
DataRow dr = ds.Tables["Devices"].NewRow();
dr["Serial"] = Serial_arr[x].Text.ToString();
dr["text"] = dynamicTextBoxes[x].Text.ToString();
ds.Tables["Devices"].Rows.Add(dr);
}
//MyLabel.Text = "der er " + deviceCount +" Devices<br />";
//foreach (TextBox tb in Serial_arr)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
//MyLabel.Text += "<br />";
//foreach (TextBox tb in dynamicTextBoxes)
//{
// MyLabel.Text += tb.Text + " :: ";
//}
}
protected void btnAddTextBox_Click(object sender, EventArgs e)
{
}
protected void btnRemoveTextBox_Click(object sender, EventArgs e)
{
}
}
Thanks For all the help anyway :)
Hope somebody can use this.
Best regards Kasper :)

Add ValidationControls dynamically to updatepanel? [ASP.NET]

I have a problem with my dynamic updatepanel that I've created.
The problem is that i want to add a validator,i.e RequriedFieldValidator, to every element that i'm creating on the serverside.
This above works fine.
But when i'm clicking the submit button it does nothing. I can see in the htmlShellcode that a span element is there showing the error, but it has the "style="visibility=hidden".
How do i solve this issue? i'm not really sure i'm doing it right from the beginning either(very new to programming).
MARKUP:
<asp:Panel ID="UpdatepanelWrapper" CssClass="Updatepanelwrapper" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:PlaceHolder runat="server" ID="WholeWrapper">
<asp:PlaceHolder runat="server" ID="QuestionWrapper">
<asp:PlaceHolder runat="server" ID="LabelQuestion"><asp:PlaceHolder>
<asp:PlaceHolder runat="server" ID="Question"></asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</asp:PlaceHolder>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnAdd" EventName="Click" />
<asp:AsyncPostBackTrigger ControlID="btnDelete" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
<asp:Panel ID="ButtonPanel" CssClass="ButtonPanel" runat="server">
<asp:ImageButton ID="btnDelete" runat="server" ImageUrl="~/Images/Deleteicon.png" CssClass="DeleteButton" OnClientClick="btnDelete_Click" />
<asp:ImageButton ID="btnAdd" runat="server" ImageUrl="~/Images/Addicon.png" CssClass="AddButton" OnClientClick="btnAddQuestion_Click" />
</asp:Panel>
</asp:Panel>
SERVERSIDE CODE: (Override method OnInit is the important one)
public partial class _Default : Page
{
static int CountOfQuestions = 1;
private RequiredFieldValidator[] ArrRequiredFieldQuestion;
private Panel[] ArrWholePanel;
private Panel[] ArrQuestionPanel;
private Label[] ArrQuestionLabel;
private TextBox[] ArrQuestionBox;
protected void Page_Load(object sender, EventArgs e)
{
}
private void LoadControls()
{
Control myControl = GetPostBackControl(this.Page);
if (myControl != null)
{
if (myControl.ID.ToString() == "btnAdd") //Ändra till btnAddQuestion om en "button" ska användas
{
CountOfQuestions++;
}
if (myControl.ID.ToString() == "btnDelete")
{
CountOfQuestions--;
}
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (!IsPostBack)
{
CountOfQuestions = 1;
}
LoadControls();
ArrRequiredFieldQuestion = new RequiredFieldValidator[CountOfQuestions];
ArrWholePanel = new Panel[CountOfQuestions];
ArrQuestionPanel = new Panel[CountOfQuestions];
ArrQuestionLabel = new Label[CountOfQuestions];
ArrQuestionBox = new TextBox[CountOfQuestions];
for (int i = 0; i < CountOfQuestions; i++)
{
RequiredFieldValidator ReqFieldQuestion = new RequiredFieldValidator();
PlaceHolder WholeWrapper = UpdatePanel1.FindControl("WholeWrapper") as PlaceHolder;
Panel WholePanel = new Panel();
Panel QuestionPanel = new Panel();
Panel CorrectAnswerPanel = new Panel();
Label QuestionLabel = new Label();
TextBox Question = new TextBox();
QuestionLabel.Text = "Write your question";
Question.TextMode = TextBoxMode.MultiLine;
Question.Width = 550;
Question.Height = 50;
WholePanel.ID = "WholePanel" + i.ToString();
QuestionPanel.ID = "QuestionPanel" + i.ToString();
Question.ID = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ID = "Validate" + i.ToString();
ReqFieldQuestion.ControlToValidate = "tbxQuestion" + i.ToString();
ReqFieldQuestion.ValidationGroup = "QuestionGroup";
ReqFieldQuestion.ErrorMessage = "Error";
ReqFieldQuestion.Attributes.Add("runat", "server");
QuestionPanel.CssClass = "QuestionEntry";
QuestionPanel.Controls.Add(QuestionLabel);
QuestionPanel.Controls.Add(Question);
QuestionPanel.Controls.Add(ReqFieldQuestion);
WholeWrapper.Controls.Add(WholePanel);
WholePanel.Controls.Add(QuestionPanel);
ArrRequiredFieldQuestion[i] = ReqFieldQuestion;
ArrQuestionPanel[i] = QuestionPanel;
ArrQuestionLabel[i] = QuestionLabel;
ArrQuestionBox[i] = Question;
}
}
protected void btnAddQuestion_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
protected void btnDelete_Click(object sender, EventArgs e)
{
//Handeld by Pre_init and LoadControls
}
public static Control GetPostBackControl(Page thePage)
{
Control postbackControlInstance = null;
if (postbackControlInstance == null)
{
for (int i = 0; i < thePage.Request.Form.Count; i++)
{
if ((thePage.Request.Form.Keys[i].EndsWith(".x")) || (thePage.Request.Form.Keys[i].EndsWith(".y")))
{
postbackControlInstance = thePage.FindControl(thePage.Request.Form.Keys[i].Substring(0, thePage.Request.Form.Keys[i].Length - 2));
return postbackControlInstance;
}
}
}
return postbackControlInstance;
}
But when i'm clicking the submit button it does nothing.
Since I don't see a Submit button, I'm taking a guess that you mean the Add and Remove buttons. If this is the case, the problem is that all your RequiredFieldValidators have the ValidationGroup property set to QuestionGroup but this is not set in any of your buttons.
Modify the Buttons like this:
<asp:ImageButton ID="btnAdd" runat="server" ValidationGroup="QuestionGroup" ... />

Categories

Resources