ASP.net Dynamically adding controls on Button press. Postback issue - c#

I have a user control which contains several buttons, depending on the button pressed a different control is added to the page (lets say button 1 adds a TextBox, button2 adds a label).
I have code along the lines of:
protected void but1_click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.ID = "tb1";
paramsCtrlDiv.Controls.Add(tb);
}
protected void but2_click(object sender, EventArgs e)
{
Label lb = new Label();
lb.ID = "lb1";
paramsCtrlDiv.Controls.Add(lb);
}
I then have a third button (button3) to get all controls on the page and their values. (Assume each button is only clicked once for this example).
My problem is when button3 is pressed the paramsCtrlDiv.controls array doesn't contain the controls that have been added. I know I need to add these controls at Page_Load time on each postback. My issue is as I don't know exactly what controls the user has added I don't know what I want to add a Page_Load (there could be a text box, then label, just a label or just a tb), I can't control what the user presses.
I know I could store everything in the session but I'm not sure this is an elegant solution. There can also be several instances of this control on different tabs so each one has to correctly maintain it's own control collection

Because you are doing this dynamically, you need a way of storing what your are doing so the server can recreate it with each PostBack. If you don't want to use Session, store the data in the ViewState (which will persist with the page regardless of time). Create a List<YourControlObjects> and make sure it is Serializable and then store it in the ViewState. You probably want to store the control type, location, etc. so that you can rebuild it on Page_Load each time there is a PostBack.
The problem comes down to you needing to maintain your own state for these dynamically created controls. This is just one suggestion but you could do this many different ways.

I personally would handle this using a ListView. Include all of the controls you need in the ItemTemplate with Visible=false and bind them to a small list stored in the viewstate. Programatically set the correct control visible on row databind.
Note you will have to collect your data in the controls and save it in your list before you rebind it.

Related

dynamically created listbox c#

I have to create multiple listbox and bind them as they created dynamically. I have created listbox as loop is for creating no of listbox as needed
for(int i=0;i<requirement;i++)
{
Listbox dynamiclistbox = new listbox();
//then i bind it with a list<>
//then i add listbox to a panel
panel.Controls.Add(dynamiclistbox);
}
My problem is that when i click on submit button the dynamic controls disappear as dynamic controls loose state on postback
can someone help me to create no. of listbox dynamically and bind also bind them on same button click . and get the listbox on postback
i.e, to know the selected item on listbox
You will need to put your code inside Page_Load event. If it is already there, then you probably have it inside something like
if (!Page.IsPostBack) {
//Your code
}
If that is the case, then you will need to put your code outside the if, since it is only adding the controls when it is not a postback and you need to add them when it is postback as well.
EDIT:
Currently the controls are created on button click. It is advisable to have a separate function which receives an input and generates the controls, add them to panel. Call this function from your click event. When this is correct, create an asp:HiddenField and set its Value to the input you need in the click handler. On Page_Load call your function with the Value of your HiddenField.
write code for binding in !IsPostBack section
for(int i=0;i<requirement;i++)
{
Listbox dynamiclistbox = new listbox();
dynamiclistbox.CssClass = "";
dynamiclistbox.ID = ""
dynamiclistbox.EnableViewState = true;
if (!IsPostBack){}

Dynamically Created User Control's Dropbox Items from Database resets on postback

First off, I have managed to create a web application where my dynamically created user controls are recreated and repopulated with the correct information upon postback. I am not sure what my problem is, but i hope that you will be able to help me figure it out based on my situation:
On my page i enter the number of controls to be created into a hardcoded textbox (its on the aspx page) and click the okay butten. This in turn, creates the specified number of user controls dynamically using c# in the background.
So far the desired number of dynamic controls are in a table on the page.
Next...
I have 1 textbox and 4 dropboxes on each dynamic user control. When i type a company name into the textbox field and press enter or click away (on text changed event) it autoposts back and the textbox retains the company name that i have typed in.
Based on this string the dropboxes are populated from the database. Now when i select the desired items from the dropboxes and click on the save button (located outside of the dynamic controls, on the page) it does an insert to the database, but it turns out that upon this postback the indexes from the dropboxes have been reset and the wrong values get inserted.
The following pictures show firstly, how it should be and then how it is.
Basically the company name remains in the textbox of the dynamic control, but the information i choose from the dropbox resets to the first index.
It's hard to tell what happend without code, but this is a common mistake:
If you fill/create the dropdownlist controls in the page load event and you post back, the code will refill/recreate the controls. That's why you have to use something like If(!IsPostBack) in your page load event. Otherwise it will execute that code everytime you do a postback and actually just want to execute the code in your event handler for that button.
If you're dynamically creating the controls, make sure to do that in the Page_Init event. Dynamic controls have to be recreated on every postback. Their state is restored after the Page_Init (if it is a postback), so make sure to only set their values in Page_Load if you want to overwrite them.

What is the best way to persist the usercontrol values without having to postback or to write server-side code?

Scenario: I am having a user control which has two drop down lists. The values of the second drop down is fetched and populated depending on the selection made in the first. So, the first drop down makes a postback and pulls the data for the second. The second dropdown, therefore, does not need any postbacks on any selection changes.
This user control is being used on a page in a gridview, and therefore it repeats several times depending on the number of records in the grid.
Problem: When I make a selection in any of the dropdowns, my previous selections in all the user control dropdowns are lost and reset to the first item in the dropdown list.
Solution that works for me: I am able to fix this behavior by setting the selections made in viewstate on SelectedIndexChanged event for the respective DropDownList. But I want to avoid the postback being made by the second dropdown as it does not do anything related to UI (changing or pulling additional data to update on screen) and from the user perspective, its a waste of time and thus irritating.
I have also tried using javascript to write the values I want to persist into hidden fields, but the hidden field values are empty when the page is refreshed.
So, What is the best way to persist the dropdown values without having to postback or to write server-side code?
Thanks in advance.
#Aniruddha , I guess you are filling the first dropdown at the page load of UserControl so write that code in !IsPostBack constraint, i.e.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack){
// Write your existing drop down bind or other code here.
}
}
Aniruddha you are probably binding you grid in the Page_Load and so in this case bind the grid under constraint of !IsPostBack as above
Hope this will help you !!

how do I save custom user control viewstate during postback?

I have written the user control InputDetails that has a few text boxes and a few radio boxes inside it.
I add it dynamically during Page_Load:
if(!Page.IsPostBack()){
InputDetails input = (InputDetails)Page.LoadControl("InputDetails.ascx");
PlaceHolder1.Controls.Add(input);
}
but when I refresh the page, the control is gone, so I'm asking, how do I save the user control in the viewstate that it has been added, so it automatically reloads it next time. Better yet, how do I read the values put in the text boxes of the user control when the page is posted back? I need to be able to add multiple InputDetails on a single page so saving it would be useful.
If you add a control to the page dynamically, you have to recreate it after each postback.
Try to remove the if (Page.IsPostBack()) line and check if it works :).
For each control you create, you should also set the same ID value each time it's created.
If there are no other issues, the ViewState should then be able to save state of the controls across postbacks.
In order to read the values, you can:
add some public properties to your user control in order to get access to the values you need
or
use TextBox txtBox = (TextBox)myCustomControlObject.FindControl("nestedTextBox") method to find (more information here: http://msdn.microsoft.com/en-us/library/486wc64h.aspx)
You can load user controls / server control dynamically using AJAX also and viewstate requires controls ID to store the viewstate properly.
would you pls go through this link for more info

How to create a copy/link of a user element in a tab control?

I have a .NET forms application using a tab control with several tabs. There are a few elements (a button and a few text boxes) that need to be displayed on every tab. Rather than create 5 seperate elements (including all the appropriate properties), is there a way to create "links" to one element?
For example, when an event occurs, I need a textbox to display the same information in each tab. As it stands, I need to create a new textbox for each tab, then explicitly write to each. It would be easiest to just write to one textbox, then consider the rest "links" which automatically update.
Those controls really ought to be somewhere else than on a TabPage. But you can get what you want by implementing the SelectedIndexChanged event and change the Parent of the control. This sample code keeps the text box on the selected tab:
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) {
textBox1.Parent = tabControl1.SelectedTab;
}
Sorry, there isn't any way to do this. controls on a form are childen of that form, they can't be simultaneously children of multiple forms. (a tab is basically a sub-form).
You could either create an array of references to all of the textboxes that you want to behave the same, and and write to all of them when you write to one of them. Or
keep the text in some location outside of the textbox, and update the textbox on the visible tab when ever the user changes tabs.

Categories

Resources