Get dynamically created element by ID in C# [duplicate] - c#

I have stumbled across a problem with my asp.net form.
Within my form the end user chooses a number of textboxes to be dynamically created, this all works fine with the following code:
protected void txtAmountSubmit_Click(object sender, EventArgs e)
{
int amountOfTasks;
int.TryParse(txtAmountOfTasks.Text, out amountOfTasks);
for (int i = 0; i < amountOfTasks; i++)
{
TextBox txtAddItem = new TextBox();
txtAddItem.ID = "txtAddItem" + i;
txtAddItem.TextMode = TextBoxMode.MultiLine;
questionNine.Controls.Add(txtAddItem);
txtList.Add(txtAddItem.ID);
}
}
However this has also caused a small problem for me, later on in my form on the submit button click, I send the results to the specified person it needs to go to (using smtp email). Again this part is fine, until I am trying to retrieve the text from these dynamically created textboxes.
What I have tried
I have tried using this msdn access server controls ID method however this was not working.
I tried to add these new textboxes to a list, however I was unsure on how to update these textboxes when they have text in them. Therefore my results were returning null because of this.
I have also looked at other questions on SO such as this however they are usually for WPF or winforms, rather than my problem with asp.net (this usually isn't an issue, but I don't need to get the text from every textbox control in my page, just the ones that were dynamically created).
I have also tried changing how I call the code that I hoped would have worked:
string textboxesText = string.Join("\n", txtList.Select(x => x).ToArray());
and then in my concatenated string (email body) I would call:
textboxesText
The problem
As they are dynamically created I am finding it difficult to call them by their id for example: txtExampleID.Text, also as I have to increment the ID's by one each time (so they don't override each other) it has made things a little bit more difficult for me.
I am not asking for a code solution, I would prefer pointers in the right direction as I am still learning.
So to sum it all up: I need to get the text from my dynamically created textboxes to add it to my email body.

The issue is these text boxes need recreated in the Load event of the page, every single time, so that both events and values can be hooked back up and retrieved.
I think the most straight forward approach, in your case, would be to extend idea #1 that you had already tried. Build a List of these controls with enough information to recreate them in Load, but you need to store that List in either ViewState or Session.
ViewState["DynamicControls"] = list;
or
Session["DynamicControls"] = list;
I would use ViewState if you can because it gets destroyed when the user leaves the page.

Related

asp.net/C# control - store value from previous page load

control (eg label) changes value when page loads.
before page load, label value is "x"
proceed to load page naturally x is lost at this point, so what is a simple way to store the value from the previous page
load?
It sounds like what you want is a history of previous states of the page, or at least just one previous value. I can suggest a way to do this, but with a caveat: Don't overuse it. You can persist data between posts in ViewState but that data gets written to the page itself. That way when the users posts the form, they're also posting that data back. (More at the end.)
Here's a simple example. First, define some class that contains all of the additional state you want to store:
[Serializable]
public class PageState
{
public string MyLabelPreviousText {get;set;}
}
Then in your code behind:
public partial class MainPage : System.Web.UI.Page
{
private PageState _pageState;
protected void Page_Load(object source, EventArgs e)
{
_pageState = ViewState["pageState"] as PageState ?? new PageState();
_pageState.MyLabelPreviousText = MyLabel.Text;
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["pageState"] = _pageState;
}
When you load the page, you're checking to see if you've already saved your class (in this case called PageState) to the ViewState. If you haven't, you create a new one.
In the PreRender event, after you're done updating the page, you're updating that class with the text of your label and then saving the whole thing to ViewState again. That way the next time the page loads you can retrieve it again.
I'm not sure at which point you want to save the previous text of your label. In this example it's saving the text during the Load event. That way if the text is changed at any point from then on, the value you have saved is the original text of the label. The details may vary depending on what you're trying to do, but this pattern lets you save that sort of custom data without using Session and piling up data like this in memory.
I mentioned not overusing it. If you save some labels, controls, and other data, ViewState probably won't get too large. ASP.NET is already putting the state of every server control there anyway. But if you go really crazy with it then ViewState can get huge. All of that data gets written to the page, and all of it gets posted back to the server with each postback.
It's probably not a huge concern, but be mindful of it. Use Chrome dev tools, Fiddler, or even just inspect your page source to see if that data is getting so large that it might impact performance.
For anyone who isn't familiar, ViewState looks like this in the HTML source:
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
value="/wEPDwULLTEyMzgxNzgyNDIPZBYCZg9kFgICAQ9kFggCAQ9kFgJmD2QWAgIBD2QWAmYPZBYMA
... etc.
As you can see, it's actually a hidden form input. ASP.NET is placing all of the details of the page's controls in the form so that when you post the form, it can piece all of that together and make sure that the page looks the same after postbacks. That's the reason why when we set up a lot of controls the first time we check if(!IsPostBack()). If it is a postback then we don't need to populate the dropdowns, etc. all over again. They are restored from that ViewState data.
This approach is functionally the same as adding an additional hidden input as suggested in one comment. The difference is that you're using an existing hidden input (viewstate) and if you need to save multiple values you're just making them properties of a class instead of adding more and more hidden inputs.
I'm not sure if this is what you mean without any code samples but I know from memory that in ASP.NET you can access the previous page property like so:
Page lastPage = currentPage.PreviousPage
Which returns the entire Page object. Assuming your label is defined like so:
<asp:label id="myLabel" runat="server" />
Then you can access the text property with:
Label myLabel = lastPage.FindControl("myLabel") as Label;
lastPageVal = myLabel.Text
So ensure that lastPageVal is a static variable, then it will also persist throughout pages.

Saving webControls in the Session object

I have a panel (pnlPanel) with lots of controls like Textboxes and DropDownLists. I want them to be persistent when the user gets back to the page, so i tried this:
/*i have saved the panel like this
Session["testPanel"] = pnlTest;
*/
protected void Page_Load(object sender, EventArgs e)
{
if (Session["testPanel"] != null)
{
panel = Session["testPanel"] as Panel;
}
}
But its not working. Is it possible? The reason why i want to do this is because overhead is not a problem, and i want to cut down on coding time.
I've never tried this myself, but this seems to me to be an extra-ordinarily bad idea. Without testing it, my guess would be that this will create a ton of ViewState problems. Even if you could maintain the ViewState, attempting to keep this control over multiple page loads would be dangerous at best.
My recommendation would be to have a common object that holds the properties of the panel you want and just build a method into one of the early events to prepopulate a new panel with those properties.
Without knowing the entire reason for doing something like this, you should have a look at output caching directives. You would be best served by pulling the content out of the panel and into a user control. Then setting output caching on control, using VaryByCustom so you can use the user name or some other unique identifier to separate by user.
http://msdn.microsoft.com/en-us/library/hdxfb6cy.aspx and
http://msdn.microsoft.com/en-us/library/system.web.httpapplication.getvarybycustomstring.aspx
Using session and/or caching will be problematic if you are in a webfarm scenario. Cache is scoped to the application instance, so another server in the web farm will not have access to it.
Some other side effects of something like this include issues with viewstate.
What you try to do here is to cache the Panel but this is not the way. The panel as you save it is a running object on the memory and can not be saved as it is. You need to convert it to html string and save and cache this string. So near the Panel you place a literal, then you render the Panel and save it on session, and then actually you display the text from this render.
if(Session["testPanel"] == null)
{
TextWriter stringWriter = new StringWriter();
HtmlTextWriter renderOnMe = new HtmlTextWriter(stringWriter);
// render and get the actually html of this dom tree
testPanel.RenderControl(renderOnMe);
// save it as cache
Session["testPanel"] = stringWriter.ToString();
}
// render the result on a literal
cLiteralID.Text = Session["testPanel"];
// hide the panel because I have render it on literal.
testPanel.Visible = false;
Need some tests as is it. I use some similar code for custom control and custom cache, never save on session this amount of data.
First Approach
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["panel"] != null)
{
panel = ViewState["panel"] as Panel;
}
}
In this approach your ViewState objects were different. You may be getting some null values once the ViewState["panel"] is given the control memory and the object is being accessed in the impression that the Session was Session["panel"]
Second Approach
Save the Complete panel HTML in database and access it on the form load by keeping the function under IsPostBack.
Now with the continuity of approach - 2 assign the value to your session object.
this.Controls.Add(new LiteralControl("Your HTML"));
Third Approach
You can use File system. Save the div in your file and access the file at runtime.
Hope this may help you.
EDIT - 1 => Added code for second approach
I had a similar problem. I tried to save an object to the View State that stored a Panel and I got an error message telling me that Panels aren't serializable. You could try using a SerializationSurrogate.
https://msdn.microsoft.com/en-us/library/system.runtime.serialization.iserializationsurrogate(v=vs.110).aspx

Adding an Response.Redirect to the same page dynamically to different Buttons on different other pages

Ok here is my problem:
I have one class (so called Drawer) that does nothing else but creating asp.net controlls dynamically depending on the data it gets.
All works fine, except the last step which is nearly independent to the content.
There is allways one button, which should allways redirect to the same page (Booking.aspx).
I want the Event to store some data in the Session Object (for example the button id) and afterwards do the redirect.
This is my code:
Button b = new Button(); // Buchenbutton
b.ID = r.getId(); // storing important id
//b.PostBackUrl = "Booking" + k + ".aspx"; // ugly workaround
//k++;
b.Text = "Choose";
b.CssClass = "AccBtn"; // styling
b.Click += new EventHandler(thisRoute(b));
the real problem is, that in this "Drawer" class i cant acces the Session.Object at least i don't know how to... and i don't know how choose the Eventhandler dynamically from the code behind of the website that calls the Drawer. I hope anyone can understand and maybe even help me... i do have this ugly workaround for more than 6 months now.
You can access the session via the HttpContext.
HttpContext.Current.Session

Prevent duplicate postback in ASP.Net (C#)

Simple one here... is there a clean way of preventing a user from double-clicking a button in a web form and thus causing duplicate events to fire?
If I had a comment form for example and the user types in "this is my comment" and clicks submit, the comment is shown below... however if they double-click, triple-click or just go nuts on the keyboard they can cause multiple versions to be posted.
Client-side I could quite easily disable the button onclick - but I prefer server-side solutions to things like this :)
Is there a postback timeout per viewstate that can be set for example?
Thanks
I dont think that you should be loading the server for trivial tasks like these. You could try some thing jquery UI blocking solution like this one. Microsoft Ajax toolkit should also have some control which does the same. I had used it a long time ago, cant seem to recall the control name though.
With jQuery you can make use of the one event.
Another interesting read is this: Build Your ASP.NET Pages on a Richer Bedrock.
Set a session variable when the user enters the page like Session["FormXYZSubmitted"]=false.
When the form is submitted check that variable like
if((bool) Session["FormXYZSubmitted"] == false) {
// save to db
Session["FormXYZSubmitted"] = true;
}
Client side can be tricky if you are using Asp.Net validation.
If you have a master page, put this in the master page:
void IterateThroughControls(Control parent)
{
foreach (Control SelectedButton in parent.Controls)
{
if (SelectedButton is Button)
{
((Button)SelectedButton).Attributes.Add("onclick", " this.disabled = true; " + Page.ClientScript.GetPostBackEventReference(((Button)SelectedButton), null) + ";");
}
if (SelectedButton.Controls.Count > 0)
{
IterateThroughControls(SelectedButton);
}
}
}
Then add this to the master page Page_Load:
IterateThroughControls(this);
I have had the same scenario. The solution of one of my coworkers was to implement a kind of Timer in Javascript, to avoid considering the second click as a click.
Hope that helps,
Disable the button on click, utilize jquery or microsoft ajax toolkit.
Depending on how important this is to you, could create an array of one time GUID's which you remove from the array once the update has been processed (ie posted back in viewstate/hidden field)
If the guid is not in the array on postback, the request is invalid.
Substitute database table for array in a clustered environment.

Disable selection box without removing value from post

In my current asp.net-mvc project one of my pages allows the user to select a value in a dropdown box after wich a post request is made that updates several values.
To make sure the delay from the postback doesn't confuse the user into selecting another value (and thus creating another post, creating another delay etc) I set the select's disabled attribute to true.
Disabled inputs aren't submitted to the post call however.
How can I make it visually clear to the user that work is in progress and make it imposible to select a new value without removing the input from the post?
Yes, this annoys me too.
Basically what you need to do is hide the old button and replace it with a disabled one so it looks the same to the user. That way it's still submitted but can't be doubly submitted.
Actually I've found what seems to be a duplicate of this at Problem with disabling submit buttons on form submit.
From your answer, I gather you are already using jQuery. In that case why don't you get the value of the select box, disable it, then post the value yourself?
Bonus : BlockUI is a nice jQuery plugin to, well, block the UI.
None of the answers I found in Cletus' post was entirely what I was looking for.
Here is what I came up with. It's not 100% reusable, but it does what I need and feel free to improve/edit.
$('#productMixSelectorForm').change(function() { $(this).ChangeSelection() });
jQuery.fn.ChangeSelection = function() {
var html = $('<div class="hidden">');
$(this).find('select, input').each(function() {
if ($(this).hasClass('hidden') == false) {
//Clone the original one into the hidden div
html.append($(this).clone());
//Disable the original (visible) one and make it's name unique again
$(this).attr("disabled", true);
var name = $(this).attr("name");
$(this).attr("name", name + "disabledDummy");
}
});
//Add the collection of clones to the form so they get submitted
$(this).append(html);
$(this).submit();
}

Categories