When I click btnGDynamicCont I want to load the first set of controls, then on each further click of that button, add a new control (textbox) alongside the other ones, so each time it is clicked I am adding a new textbox across state.
Do you know where I should add the creation of the new textbox in order to keep it after each postback?
{
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) == "true")
GenerateDynamicControls();
}
public void GenerateDynamicControls()
{
TextBox txtDynamic = new TextBox();
txtDynamic.ID = "txtDynamic";
txtDynamic.Text = "Dynamic TextBox";
Page.Form.Controls.Add(txtDynamic);
TextBox txtDynamic2 = new TextBox();
txtDynamic2.ID = "txtDynamic2";
txtDynamic2.Text = "Dynamic Textbox";
Page.Form.Controls.Add(txtDynamic2);
}
protected void btnGDynamicCont_Click1(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["Generated"]) != "true")
{
GenerateDynamicControls();
ViewState["Generated"] = "true";
}
else
{
Response.Write("<h2>Controls are already exist in page</h2>");
}
}
}
}
Dynamic controls are usually recreated at the Page_Load method. For more information, please refer to the Dynamically Created Controls in ASP.NET article.
You can refer the below link where a very similar issue is addressed.
unable to add more than one server control dynamically in asp.net
Everytime a postback happens, you should recreate the already existing controls(dynamically added) in your page_load event and the new controls are to be created in the button_click event.
Use some logic to generate ids for the controls for the viewstate to be maintained. VIEWSTATE will be taken care automatically if the ids of the controls generated before and after postback are the same.
One way to keep track of the number of textboxes is to store the count in session.
Related
I am having some trouble understanding the impact of setting checkbox visibility on the checked state at various stages in the page life cycle.
Given below is a sample code for a dynamically created checkbox.
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
check = new CheckBox();
check.AutoPostBack = true;
check.Text = "checkbox1";
check.ToolTip = "tooltip for checkbox1";
check.CheckedChanged += new EventHandler(check_CheckedChanged);
this.Form.Controls.Add(check);
Button btn = new Button();
btn.Text = "click me";
btn.Click += new EventHandler(btn_Click);
this.Form.Controls.Add(btn);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
check.Checked = true;
check.Text = "text reassigned.";
check.ToolTip = "tooltip reassigned";
}
}
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
check.Visible = false;
}
The issue here is, when a postback occurs (I click on the button), then I notice in the Page_load event, the checkbox maintains the viewstate of the tooltip and text. However the checked state is changed to false and it fires a CheckedChanged event. Why is the behavior so?
Also, if I set the visibility of the checkbox in either PageLoad() or the OnPreRender() event, the checked state of the checkbox is maintained across postbacks and does not fire a CheckedChanged event.
I'm just curious as to what happens differently when the visibility is changed in the OnPreRenderComplete event so as to have the checkbox default to an unchecked state.
Well I have marked my last answer for deletion, as I didn't understand the question properly.
Well the things you are doing are:
You added the checkbox at runtime in Init event on server side.
Then in page load you set its value to true in the Not Post Back check.
Then you set its visibility to false in OnPreRenderComplete event
When you set the visibility to false on server side, the control is not generated on client side (you can check it by viewing the page source), as control is not created on client side so when you post back the page, the checkbox is created in page init and as it was not on client side so dot net doesn't know about its last value, so you get false for the check box.
If you need to check it more further, change your OnPreRenderComplete event as:
protected override void OnPreRenderComplete(EventArgs e)
{
base.OnPreRenderComplete(e);
//check.Visible = false;
check.Style.Add("display", "none");
}
By above line, the style is being added to the control, so the control is generated on client side but is not visible and you will get its value during the post back.
I've created an application in which I've created Dynamic Controls on Click Event of a Button. But the dynamically created Control Event will not Fire on Click of it.
Below is the Code I've written.
ImageButton closeImage = new ImageButton();
closeImage.ID = "ID"+ dr["ID"].ToString();
closeImage.AlternateText = "Delete";
closeImage.ImageUrl = "App_Themes/images/CloseButton.png";
closeImage.Attributes.Add("style", "float:right;cursor:pointer;margin: -19px 1px -10px;");
closeImage.EnableViewState = true;
closeImage.CommandName = "Delete";
closeImage.CommandArgument = dr["ID"].ToString();
closeImage.Attributes.Add("runat", "server");
closeImage.OnClientClick = "return confirm('Are you sure you want to remove this');";
closeImage.Click += new ImageClickEventHandler(this.closeImage_click);
protected void closeImage_click(object sender, ImageClickEventArgs e)
{
ImageButton ibDel = (ImageButton)sender;
}
The same code work if its placed on Page_Load(). Is there any other Solution to fire the event.
I would like to suggest that you read up on the following article on MSDN. It's about page lifecycle.The key part is to when controls are created. If the controls are created in the wrong stage, events will not be registered, and thus will not fire.
http://msdn.microsoft.com/en-us/library/ms178472%28v=vs.80%29.aspx
I have a PlaceHolder control inside of a ListView that I am using to render controls from my code behind. The code below adds the controls:
TextBox tb = new TextBox();
tb.Text = quest.Value;
tb.ID = quest.ShortName.Replace(" ", "");
((PlaceHolder)e.Item.FindControl("ph_QuestionInput")).Controls.Add(tb);
I am using the following code to retrieve the values that have been entered into the TextBox:
foreach (ListViewDataItem di in lv_Questions.Items)
{
int QuestionId = Convert.ToInt32(((HiddenField)di.FindControl("hf_QuestionId")).Value);
Question quest = dc.Questions.Single(q => q.QuestionId == QuestionId);
TextBox tb = ((TextBox)di.FindControl(quest.ShortName.Replace(" ","")));
//tb is always null!
}
But it never finds the control. I've looked at the source code for the page and the control i want has the id:
ctl00_cphContentMiddle_lv_Questions_ctrl0_Numberofacres
For some reason when I look at the controls in the ListViewDataItem it has the ClientID:
ctl00_cphContentMiddle_lv_Questions_ctrl0_ctl00
Why would it be changing Numberofacres to ctl00? Is there any way to work around this?
UPDATE:
Just to clarify, I am databinding my ListView in the Page_Init event. I then create the controls in the ItemBound event for my ListView. But based on what #Womp and MSDN are saying the controls won't actually be created until after the Load event (which is after the Page_Init event) and therefore are not in ViewState? Does this sound correct?
If so am I just SOL when it comes to retrieving the values in my dynamic controls from my OnClick event?
UPDATE 2:
So i changed the code i had in my Page_Init event from:
protected void Page_Init(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//databind lv_Questions
}
}
to:
protected void Page_Init(object sender, EventArgs e)
{
//databind lv_Questions
}
And it fixed my problem. Still a little confused as to why I want to databind regardless of whether it's a postback or not but the issue is resolved.
It looks like you're adding your textbox to a Placeholder control... but then you're searching a ListViewDataItem container for it later.
Seems to me that you need to search for the Placeholder first, and then search it for the textbox.
I used to have some controls added dynamically through runtime on an ASP.NET webpage and was able to handle their events but now I put the code in a user control but it doesnt work. Any idea?
while (drr.Read())
{
LinkButton lnkbtnDownloadFile = new LinkButton();
//name of the file ---> drr[2]
lnkbtnDownloadFile.Click += new EventHandler(lnkbtnDownloadFile_Click);
lnkbtnDownloadFile.Text = drr[2].ToString();
PlaceHolderQuestions.Controls.Add(lnkbtnDownloadFile);
PlaceHolderQuestions.Controls.Add(new LiteralControl("<br/>"));
}
void lnkbtnDownloadFile_Click(object sender, EventArgs e)
{
if (sender is LinkButton)
DownloadFile((sender as LinkButton).Text);
}
so when i add a break point at the event handler it doesnt stop
I knew the reason. Because to bind the event handler with the control, the control must be drawn or initialized again, which didn't happen in my code and that's why the event wasn't fired
I am using an ASP.NET AJAX-Enabled Web application (ASP.NET 2.0 and AJAX Toolkit 1.0)
that contains one button and 2 UpdatePanels (UpdatePanel_1 and UpdatePanel_2)
The button is registered with RegisterAsyncPostBackControl in the ScriptManager object
UpdatePanel_1 is in "Conditional" update mode and contains a TextBox.
UpdatePanel_2 is in "Always" update mode and contains another TextBox
When the button is pressed its handler calls UpdatePanel_1.Update() that updates the value of the TextBox based on a randomly selected value in a list;
Also the UpdatePanel_2's TextBox is being updated automatically , also without page refresh
Based on the value of a boolean ViewState variable I would also like to hide/show the UpdatePanels alternatively but
I get the error :
"Sys.InvalidOperationException: COuld not find UpdatePanel with ID 'UpdatePanel_2' (or UpdatePanel_1).
If it is being updated dynamically then it must be inside another UpdatePanel"
How can it be done without adding extra wrapping UpdatePanels?
protected void Page_Load(object sender, EventArgs e)
{
ScriptManager1.RegisterAsyncPostBackControl(Button1);
if (!IsPostBack)
{
Visibility = true;
}
UpdatePanel_1.Visible = !Visibility;
UpdatePanel_2.Visible = Visibility;
Visibility = !Visibility;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Panel1.Visible)
UpdatePanel_1.Update();
}
protected bool Visibility
{
get
{
return (bool)(ViewState["Visibility"] ?? true);
}
set
{
ViewState["Visibility"] = value;
}
}
The problem is that invisible controls aren't rendered to the client. So then trying to make them visible isn't going to work because as far as the client is concerned, they don't exist.
Try using style="display:none", or use different CSS classes and styles for visible and invisible panels, rather than setting visible=false;
You can invisible, or visible controls is child of updatepanel, not invisible, visible updatepanel, I try use updatemode = conditional but error, and then I visible controls add to updatepanel. Hopy help you
Thanks everybody post