Add ValidationControls dynamically to updatepanel? [ASP.NET] - c#

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" ... />

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

ViewState won't hold dynamically created controls' value, even though I preserve the same ids in postbacks

I am trying to create a simple form generating webpage that user can select different controls via a DropDownList, add a Text property to it(and a GroupName property if ii was a RadioButton) and then click a button to generate that control right in the page for previewing purpose (I am also going to add another button to insert the form's information in a database but this is not my problem right now)
this is my aspx page:
<div class="main-wrapper">
<form dir="rtl" id="form" runat="server">
<label>Desired Control : </label>
<asp:DropDownList AutoPostBack="true" ID="ddlControlType" OnSelectedIndexChanged="ddlControlType_SelectedIndexChanged" runat="server">
<asp:ListItem Text="label"></asp:ListItem>
<asp:ListItem Text="text box"></asp:ListItem>
<asp:ListItem Text="check box"></asp:ListItem>
<asp:ListItem Text="radio button"></asp:ListItem>
</asp:DropDownList>
<br /><br />
<label class="label">control's text : </label>
<asp:TextBox ID="txtboxText" runat="server" CssClass="txtbox"></asp:TextBox>
<label class="label">group name (only for radio button)</label>
<asp:TextBox Enabled="false" ID="txtboxGroupName" runat="server" CssClass="txtbox"></asp:TextBox>
<br /><br />
<asp:Button ID="btnAddControl" CssClass="btn" Text="add to form" OnClick="btnAddControl_Click" runat="server" />
<hr />
<h1>form preview</h1>
<asp:Panel ID="panel" runat="server">
</asp:Panel>
</form>
this is the code behind:
public Dictionary<string, Type> ControlTypes
{
get { return (Dictionary<string, Type>)Session["ControlTypes"]; }
set { Session["ControlTypes"] = value; }
}
public int NumberOfControls
{
get { return (int)ViewState["NumOfControls"]; }
set { ViewState["NumOfControls"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.NumberOfControls = 0;
ControlTypes = new Dictionary<string, Type>();
}
else
this.CreateControls();
}
private void CreateControls()
{
for (int counter = 0; counter < this.NumberOfControls; counter++)
{
string controlId = "control_id_" + counter.ToString();
Type controlType = ControlTypes[controlId];
PropertyInfo[] properties = controlType.GetProperties();
object controlObject = Activator.CreateInstance(controlType);
foreach (var property in properties)
{
if (property.Name == "ID")
property.SetValue(controlObject, controlId, null);
}
panel.Controls.Add(controlObject as Control);
}
}
protected void ddlControlType_SelectedIndexChanged(object sender, EventArgs e)
{
switch (ddlControlType.SelectedIndex)
{
case 0:
case 2:
txtboxText.Enabled = true;
txtboxGroupName.Enabled = false;
break;
case 1:
txtboxText.Enabled = false;
txtboxGroupName.Enabled = false;
break;
case 3:
txtboxText.Enabled = true;
txtboxGroupName.Enabled = true;
break;
}
}
protected void btnAddControl_Click(object sender, EventArgs e)
{
Control tempControl = null;
switch (ddlControlType.SelectedIndex)
{
case 0:
tempControl = new Label();
((Label)tempControl).Text = txtboxText.Text;
break;
case 1:
tempControl = new TextBox();
break;
case 2:
tempControl = new CheckBox();
((CheckBox)tempControl).Text = txtboxText.Text;
break;
case 3:
tempControl = new RadioButton();
((RadioButton)tempControl).Text = txtboxText.Text;
((RadioButton)tempControl).GroupName = txtboxGroupName.Text;
break;
}
string controlId = "control_id_" + this.NumberOfControls.ToString();
tempControl.ID = controlId;
panel.Controls.Add(tempControl);
this.NumberOfControls++;
ControlTypes.Add(controlId, tempControl.GetType());
}
as you can see, I preserve the id's of the controls, but the viewstate won't update their values.the controls will be added to the form with the desired id, but its values won't be set at all
what should I do?

How to retain gridview data when postback?

I have fill data in grid view. And also i have written in code inside Row Data Bound for changing image URL to image.
Here is the code:
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
if(cellValue.StartsWith("http:"))
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = e.Row.Cells[i].Text.Trim();
HyperLink hb = new HyperLink();
hb.Controls.Add(img);
e.Row.Cells[i].Controls.Add(hb);
}
}
}
It is working fine. The page has another two drop down controls. If i select one drop down control, i made post back. At that time, the image inside i already wrote is changed to URL instead of Image.
Can you any one assist me to handle?
Thanks in advance.
Here is my code for the issues(i am not able to post entire code)
aspx code:
<html>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList2" CssClass="borderradius" runat="server" Height="20px" Width="190px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Font-Size="11px">
</asp:DropDownList>
<asp:Button id="sidesbmt" runat="server" onclick="sidesbmt_click"/>
<asp:GridView ID="GridView1" runat="server" Width="100%" CssClass="mGrid" PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
BorderStyle="None" GridLines="Both">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</body>
</html>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sidesbmt_Click(object sender, EventArgs e)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
if(cellValue.StartsWith("http:"))
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = e.Row.Cells[i].Text.Trim();
HyperLink hb = new HyperLink();
hb.Controls.Add(img);
e.Row.Cells[i].Controls.Add(hb);
}
}
}
This problem happens when you add controls dynamically and this control does not exist during the Page Init event. To restore the viewstate to the control after postback, the control has to be present in the control tree.
You can try changing your code a bit like this.
Conver the column which displays the image and url into template field
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="literalUrl" Text='<%#Eval("The fieldname")%>'></asp:Literal>
<asp:Image runat="server" ID="imageUrl" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
Then in the rowdatabound event toggle the view of image and literal
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
Literal literal = e.Row.Cells[i].FindControl("literalUrl") as Literal;
Image imageUrl = e.Row.Cells[i].FindControl("imageUrl") as Image;
if (literal != null && imageUrl != null)
{
if (literal.Text.StartsWith("http:"))
{
imageUrl.ImageUrl = literal.Text.Trim();
imageUrl.Viisible = true;
literal.Visible = false;
}
}
}
}

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 :)

Ajax Timer: Execute only 5 times

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..

Categories

Resources