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
Related
I am using Asp.Net Gridview inside which there are 2 columns. First Column has a dropdown and depending on the selection I am dynamically adding a control inside second column like it may be a TextBox, Dropdown ,etc. This is working fine. Now if i want to retrieve the value from that TextBox entered by the user what can I do?
Below is my code :
ASPX Page :
<asp:GridView ID="CRFormGridView" runat="server" AutoGenerateColumns="false"
OnRowDataBound="CRFormGridView_RowDataBound" AllowPaging="true" PageSize="25" ClientIDMode="Static" OnDataBound="CRFormGridView_DataBound">
<Columns>
<asp:BoundField DataField="CRListID" HeaderText="CR List ID" Visible="false" />
<asp:TemplateField HeaderText="Change Type">
<ItemTemplate>
<asp:UpdatePanel ID="updtpnlChangeType" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList Width="150" runat="server" ID="ddlChangeType" ClientIDMode="Static" AutoPostBack="true" OnSelectedIndexChanged="ddlChangeType_SelectedIndexChanged">
<asp:ListItem Text="" Value="0"></asp:ListItem>
<asp:ListItem Text="Update Offer" Value="1"></asp:ListItem>
<asp:ListItem Text="Add Component" Value="2"></asp:ListItem>
<asp:ListItem Text="Cancel Component" Value="3"></asp:ListItem>
<asp:ListItem Text="Update Request" Value="4"></asp:ListItem>
<asp:ListItem Text="Add Request" Value="5"></asp:ListItem>
<asp:ListItem Text="Cancel Request" Value="6"></asp:ListItem>
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Change Sub Type">
<ItemTemplate>
<asp:UpdatePanel ID="updtpnlChangeSubType" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:DropDownList Width="150" runat="server" ID="ddlChangeSubType" ClientIDMode="Static" AutoPostBack="true" OnSelectedIndexChanged="ddlChangeSubType_SelectedIndexChanged">
</asp:DropDownList>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Request/Comments">
<ItemTemplate>
<asp:UpdatePanel ID="updtpnlDynamicControl" runat="server" ClientIDMode="Static" UpdateMode="Conditional">
<ContentTemplate>
<asp:PlaceHolder ID="placehldrDynamicCnrtl" runat="server" ClientIDMode="Static" OnPreRender="placehldrDynamicCnrtl_PreRender"></asp:PlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Cs Page Code :
protected void ddlChangeType_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlChangeType = (DropDownList)sender;
GridViewRow currentRow = (GridViewRow)ddlChangeType.NamingContainer;
DropDownList ddlChangeSubType = currentRow.FindControl("ddlChangeSubType") as DropDownList;
object objControl;
if (ddlChangeSubType != null && currentRow != null && ddlChangeType != null)
{
ddlChangeSubType.DataTextField = "Desc";
ddlChangeSubType.DataValueField = "ID";
ddlChangeSubType.DataSource = setChangeSubType(ddlChangeType.SelectedValue);
ddlChangeSubType.DataBind();
if (Session["DynamicControls"] != null)
{
for (int y = 0; y < CRFormGridView.Rows.Count; y++)
{
if (((Dictionary<int, object>)Session["DynamicControls"]).TryGetValue(y, out objControl))
{
if (currentRow.RowIndex == y)
objControlsDict.Remove(y);
else
objControlsDict.Add(y, objControl);
}
}
}
Session.Add("DynamicControls", objControlsDict);
}
}
protected void ddlChangeSubType_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddlChangeSubType = (DropDownList)sender;
GridViewRow currentRow = (GridViewRow)ddlChangeSubType.NamingContainer;
DropDownList ddlChangeType = currentRow.FindControl("ddlChangeType") as DropDownList;
//TextBox txt = currentRow.FindControl("txt") as TextBox;
PlaceHolder placehldr = currentRow.FindControl("placehldrDynamicCnrtl") as PlaceHolder;
object objControl;
rowIndex = currentRow.RowIndex;
if (Session["DynamicControls"] != null)
{
for (int y = 0; y < CRFormGridView.Rows.Count; y++)
{
if (((Dictionary<int, object>)Session["DynamicControls"]).TryGetValue(y, out objControl))
{
objControlsDict.Add(y, objControl);
}
}
}
if (ddlChangeSubType != null && currentRow != null && ddlChangeSubType != null)
{
switch (ddlChangeType.SelectedItem.Text.ToUpper())
{
case "UPDATE OFFER":
TextBox txtBox = new TextBox();
txtBox.Text = "Text Box Added";
txtBox.ID = "txt";
txtBox.ClientIDMode = ClientIDMode.Static;
txtBox.EnableViewState = true;
placehldr.Controls.Add(txtBox);
if (objControlsDict.ContainsKey(rowIndex))
objControlsDict.Remove(rowIndex);
objControlsDict.Add(rowIndex, txtBox);
break;
case "ADD COMPONENT":
Label lbl = new Label();
lbl.Text = "Label Added";
lbl.ID = "lbl";
lbl.ClientIDMode = ClientIDMode.Static;
lbl.EnableViewState = true;
placehldr.Controls.Add(lbl);
if (objControlsDict.ContainsKey(rowIndex))
objControlsDict.Remove(rowIndex);
objControlsDict.Add(rowIndex, lbl);
break;
case "UPDATE REQUEST":
break;
default:
break;
}
Session.Add("DynamicControls", objControlsDict);
}
}
protected void placehldrDynamicCnrtl_PreRender(object sender, EventArgs e)
{
try
{
if (Page.IsPostBack)
{
PlaceHolder placeHldr = (PlaceHolder)sender;
GridViewRow currentRow = (GridViewRow)placeHldr.NamingContainer;
objControlsDict = (Dictionary<int, object>)Session["DynamicControls"];
if (objControlsDict != null)
{
if (objControlsDict.ContainsKey(count) && objControlsDict[count] is TextBox)
{
TextBox txtBox = (TextBox)objControlsDict[count];
txtBox.Text = "Text Box Added";
txtBox.ID = "txt";
txtBox.ClientIDMode = ClientIDMode.Static;
txtBox.EnableViewState = true;
((PlaceHolder)this.CRFormGridView.Rows[count].Cells[3].FindControl(
"placehldrDynamicCnrtl")).Controls.Add(txtBox);
}
if (objControlsDict.ContainsKey(count) && objControlsDict[count] is Label)
{
Label lbl = (Label)objControlsDict[count];
lbl.Text = "Label Added";
lbl.ID = "lbl";
lbl.ClientIDMode = ClientIDMode.Static;
lbl.EnableViewState = true;
((PlaceHolder)this.CRFormGridView.Rows[count].Cells[3].FindControl(
"placehldrDynamicCnrtl")).Controls.Add(lbl);
}
count++;
}
}
}
catch (Exception es)
{
throw;
}
}
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.
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" ... />
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..
I am using c# for programming!
Below is my aspx code where I am using timer control in UpdatePanel.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" RenderMode="Inline" UpdateMode="Always">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="20000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:HiddenField ID="hidCurrentDate" runat="server" />
<asp:HiddenField ID="hidTripIds" runat="server" />
<asp:HiddenField ID="hidTripDetails" runat="server" />
<asp:HiddenField ID="currPageNo" runat="server" Value="1" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>
And below is the code of my aspx.cs for timer_tick event.
protected void Timer1_Tick(object sender, EventArgs e)
{
DataTable dtTrips = null;
WEX.Prototype.Data.TripDA tripDA = new WEX.Prototype.Data.TripDA();
TripSummaryBO tripSummaryBO = new TripSummaryBO();
string tID = hidTripIds.Value.TrimStart(',');
if (!string.IsNullOrEmpty(tID))
{
string[] tripIDs = tID.Split(',');
string status = string.Empty;
foreach (string tripID in tripIDs)
{
tripSummaryBO = tripDA.getTripSummary(Convert.ToInt32(tripID));
if (tripSummaryBO.tripLastEditedOnDate > Convert.ToDateTime(hidCurrentDate.Value))
{
if (string.IsNullOrEmpty(status))
{
status = tripSummaryBO.tripID.ToString();
}
else
{
status = status + "," + tripSummaryBO.tripID.ToString();
}
if (cnt == 0)
{
hidTripDetails.Value = ("Trip name-" + tripSummaryBO.tripName + " was modified by user " + tripSummaryBO.tripLastEditedBy);
}
else
{
hidTripDetails.Value = hidTripDetails.Value + "--" +("Trip name-" + tripSummaryBO.tripName + " was modified by user " + tripSummaryBO.tripLastEditedBy);
}
cnt = cnt + 1;
}
}
if (!string.IsNullOrEmpty(status))
{
string alertMessage = "alert('" + hidTripDetails.Value + "');";
Guid numb = Guid.NewGuid();
ScriptManager.RegisterClientScriptBlock(upTripsGrid, upTripsGrid.GetType(), numb.ToString(), alertMessage, true);
WEX.Prototype.Service.WSProxies WSProxies = new WEX.Prototype.Service.WSProxies();
dtTrips = WSProxies.Build();
Session["AllTrips"] = dtTrips;
dtTrips = (DataTable)Session["AllTrips"];
BuildGridViewControl(dtTrips);
}
hidCurrentDate.Value = DateTime.Now.ToString();
}
}
You can see that I am using below code for showing alert however its not coming up!
ScriptManager.RegisterClientScriptBlock(upTripsGrid, upTripsGrid.GetType(), numb.ToString(), alertMessage, true);
Please suggest!
Thanks.
What is "upTripsGrid" in you code?
If you're using this code, with the above aspx-code, try using "UpdatePanel1" instead of "upTripsGrid"?