I've been having a tough time with updating my text boxes and could really use some help. So basically, I have a popup panel for the user to select a value that I then populate into a certain text box.
I am certain that the problem is either very simple to solve, or that I'm confused on what post back actually does. Here is a snippit of my code below:
protected void grvSearchRecords_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (string.Compare(e.CommandName, "EditRow", true) == 0)
{
long nMagic2Value = Convert.ToInt64(e.CommandArgument);
string tmp = GetItem(nMagic2Value, currentTableName);
textBox1.Text = tmp;
Debug.WriteLine(textBox1.Text.ToString());
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "SearchRecords", "$(document).ready(function(){ $('#mask, #divSearchRecordsGrid').fadeOut(\"fast\"); });", true);
}
}
The "tmp" variable grabs the value I need and assigns it to the text box.
I then run a Debug statement and confirm that the value is correctly assigned to the box. As soon as the function ends, however, that assigned value is lost, and the text box never populates with the new value.
Wrap your code around a post back check
if (!IsPostBack)
{
//your code here
}
This will ensure that your code does not run when it is a post back, so your textBox will not be clear.
Post back means that the page is not being rendered for the first time, for example a page refresh.
Okay, I just got it working. The textbox I was trying to change was part of a Content tag and nothing else. I enclosed it in an UpdatePanel and added a trigger for my GridView, and now it works!
The joys of learning a new language.
Related
From research, the answer to my question seems to be a resounding no.
From Rob de la Cruz's answer here and Jonathan Wood's answer here, it seems that the only way to do it is to use JavaScript. Sadly, I don't have the necessary skill level to implement their solutions and I'm not completely sure it will work for my situation anyway. See what you think:
What I have (using asp.net and C# in VS2019) is a treeview control which:
1.1 At the first level, displays the names of customers.
1.2 Expand a customer node and the next level displays a list of sales order numbers for that customer.
1.3 Expand a sales order node and the third and final level displays a list of the sale items belonging to that particular sales order.
Pretty standard stuff I should imagine. Now, also pretty standard is that, when a node is clicked a procedure will make visible a formview which displays information about that object. When a customer node is clicked it will display the customer formview. When a sales order node is clicked it will display a sales order formview. When a sale item node is clicked... you can probably guess what it displays then.
And this is where things start to go off the rails. When a node is clicked, it's Value property is stored in a variable called _id. This variable is then stored in ViewState. When the PostBack happens, the idea is that the Page_Load event will read the value of _id from ViewState, run the showFormViews() procedure and display the relevant formview. I have it laid out like this:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["_id"] == null)
{
_id = "";
}
else
{
_id = Convert.ToString(ViewState["_id"]);
}
if (!IsPostBack)
{
fillTreeView;
tv.CollapseAll();
}
showFormViews();
}
and when a node is clicked:
protected void tv_SelectedNodeChanged(Object sender, EventArgs e)
{
// (a) PostBack occurs and Page_Load is run *before* _id is set and stored in ViewState
_id = tv.SelectedNode.Value;
ViewState.Add("_id", _id);
showFormViews();
// (b) would be great to be able to fire off a PostBack programmatically right here!
}
(the .aspx markup is just a TreeView and three FormViews linked to ObjectDataSources)
As I now know from this helpful page:
"The initialisation part of the page lifecycle will execute before the
event handler of the control that caused the post back. Therefore the
code in the page’s Init and Load event handler will execute before the
code in the event handler for the button that the user clicked."
As written at line (a) above, when the treeview node is clicked, the page is posted back and Page_Load is run whilst _id is still null. Because _id is null the showFormViews() procedure hides all of the formviews.
Then the SelectedNodeChanged event fires, _id is set and the showFormViews() procedure sets the relevant formview to visible. But of course, by now all of the controls have been rendered and so... nothing happens.
Being able to somehow fire a PostBack at line (b) would work out wonderfully. Page_Load would fire and run showFormViews() but this time with _id being what it should be.
Various variations at line (b) of:
Server.Transfer("samePage.aspx");
// or
Response.Redirect(Request.RawUrl, false);
don't work because they destroy ViewState (unless someone knows different?) so _id is back to being null again.
So if you can't fire off a PostBack in C# and if I can't work out how to implement the solutions by the two posters above (or even if they will be appropriate in this situation), is there any way I can restructure the page to make this - a fairly common pattern I would imagine - work (and please don't suggest MVC - I tried learning that and still have the nightmares!).
Many thanks in advance,
You can call in your PageLoad the method used to fill the ViewState... Like:
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["_id"] == null)
{
_id = "";
}
else
{
_id = Convert.ToString(ViewState["_id"]);
tv_SelectedNodeChanged(null, null);
}
if (!IsPostBack)
{
fillTreeView;
tv.CollapseAll();
}
}
I have a bit of an issue I hope you guys can give me a bit of help with.
I have an ASP.NET textbox control. In my code behind I throw text in there with
txtTextbox.Text = variable;
Variable being a value I get from a database in earlier lines of code.
So after this, when I edit the text in that text box, in the button click event handler I get the new value with
string variable = txtTextbox.Text;
The issue is, now this 'new' value is just giving me the original value I placed in the textbox. Not the one I eddited in my application.
Any help greatly appreciated. Thanks.
Need to check for post back when loading data in to textbox,
Otherwise data gets binded to textbox when button click happens
if(!IsPostback)
{
//load data
}
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.
I'm working on an application where the users guesses on a number (7 trues). The app contains of an input field as well as a button, and if the user hasn't got more guesses the input field as well as the button is disabled, and a new button appears (restart).
In my code behind-file is the code for checking if the user has more guesses or not, and if not the following code takes care of the disabling/enabling of the buttons:
code behind-file:
...
btnCheckNr.Enabled = false;
inputBox.Enabled = false;
newGame.Visible = true;
...
I'm not using ViewState but Session state, and every time a postpack is done the fields is back as they were from the start, ie. enabled. Every time the user has made a guess the input field gets focus and the content inside (eg. last guess made) gets selected. This works accept for when the field and button gets disabled, and by that reason I've added a check to see if the input field is disabled or not. If so, focus and selection shall not be done (otherwise I get an error).
However, with this code the input field never gets focus, why is that? Is it something that I'm doing wrong and in that case how could this be accomplished?
Thanks in advance!
external.js:
var Capsule = {
init: function() {
var input = $('#inputBox');
if (!input.is(":disabled"))
input.focus();
input.select();
}
}
}
window.onload = Capsule.init;
Try triggering a click instead:
input.click().select();
Demo.
I have a GView and I am populating rows from code behind. However, in the RowUpdating event I want to access the changes done by the user and store that change into a string. Here is my code:
protected void gvShowComm_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
System.Web.UI.WebControls.TextBox myBox = gvShowComm.Rows[e.RowIndex].FindControl("PlanName") as System.Web.UI.WebControls.TextBox;
string s = myBox.Text;
gvShowComm.DataBind();
}
string s is still showing me the OLD text which is populated before. I want to store new string which user entered. How do I do that?
make sure you repopulate rows and call DataBind at least on PageLoad, preferably on OnIniti without doing that, you always get values from viewstate (if you didnt disable it). at a last resort, you can investigate Request.Form and find if you recieved new value properly
Can't you use e.NewValues[] . The result that you are getting is probably e.OldValues[]