i have about 4 textboxes on my webpage...some are asp:textboxes while others are input type="text".
the input textbox is populated through a javascript popup calender control while asp.net textbox is populated by typing. The initial values of these textboxes are retrieved from a database.
When a user changes these values, they are not saved and the textboxes are cleared out after the submit button is clicked. Please help resolve this confusion. Thanks.
thanks for your reply but it is still not working.....
i have put this code in my page load event
if (Page.IsPostBack)
{
if (ViewState["stock"] != null)
TextBoxMaterial.Text = ViewState["stock"].ToString();
if (ViewState["supplier"] != null)
TextBoxSupplier.Text = ViewState["supplier"].ToString();
if(ViewState["matTime"] != null)
TextBoxMatTime.Text = ViewState["matTime"].ToString();
if(ViewState["prodTime"] != null)
TextBoxProdTime.Text = ViewState["prodTime"].ToString();
if (ViewState["shipTime"] != null)
TextBoxShipTime.Text = ViewState["shipTime"].ToString();
if(ViewState["cmr"] != null)
cmrDue.Value = ViewState["cmr"].ToString();
if(ViewState["kc"] != null)
kcDue.Value = ViewState["kc"].ToString();
}
and also put the below code in the onclick event for the button
ViewState["stock"] = TextBoxMaterial.Text;
ViewState["supplier"] = TextBoxSupplier.Text;
ViewState["matTime"] = TextBoxMatTime.Text;
ViewState["prodTime"] = TextBoxProdTime.Text;
ViewState["shipTime"] = TextBoxShipTime.Text;
ViewState["cmr"] = cmrDue.Value.ToString();
ViewState["kc"] = kcDue.Value.ToString();
string prodLine = DDProdLine.SelectedValue;
string stock1 = DDMaterial.SelectedValue;
string stock2 = ViewState["stock"].ToString();
string supplier = ViewState["supplier"].ToString();
string billet = RBBillet.SelectedValue;
string matTime1 = ViewState["matTime"].ToString();
string matTime2 = DDMatTime.SelectedValue;
string prodTime1 = ViewState["prodTime"].ToString();
string prodTime2 = DDProdTime.SelectedValue;
string shipTime1 = ViewState["shipTime"].ToString();
string shipTime2 = DDShipTime.SelectedValue;
CultureInfo cultureInfo = CultureInfo.CurrentCulture;
string format = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern.ToString();
string cmr = ViewState["cmr"].ToString();
string kc = ViewState["kc"].ToString();
string x = cmr.Substring(3, 2);
string y = cmr.Substring(0, 2);
string z = cmr.Substring(6, 4);
string x1 = kc.Substring(3, 2);
string y1 = kc.Substring(0, 2);
string z1 = kc.Substring(6, 4);
string finalCmr = x + "/" + y + "/" + z;
string finalKC = x1 + "/" + y1 + "/" + z1;
DateTime dt = DateTime.ParseExact(finalCmr, format, cultureInfo);
DateTime cr = DateTime.ParseExact(finalKC, format, cultureInfo);
string custDate = dt.ToString("dd/mm/yyyy");
string kcDate = cr.ToString("dd/mm/yyyy");
string id = Request.QueryString["id"];
bool success = true;
TextBoxProdComment1.Text = stock2 + "," + supplier + matTime1 + "," + prodTime1 + "," + shipTime1 + "," + custDate
+ "," + kcDate;
try
{
success = CRTopButtons.SaveProdTable(id, prodLine, stock1, supplier, billet, matTime1, matTime2, prodTime1,
prodTime2, shipTime1, shipTime2, custDate, kcDate);
}
catch (Exception e)
{
TextBoxProdComment2.Text = e.Message;
System.Diagnostics.Trace.Write(e.StackTrace);
}
the textboxes still clear out and none of it is readonly..........
please help
I had a similar problem and The Solution to "Losing data changed by javascript during postback"
is best described by this article
ViewState and Readonly Property of Textbox
for example let's say we have this asp.net control:
<asp:TextBox ID="txtName" runat="server" EnableViewState= "false" ReadOnly="true" />
if you change the value of this control through javascript in the client side it will not be propagated via postback in the serverside...whatever you do with javascript unless you remove readonly="true". Now there is a solution to this problem as described in the article above.
Simply put this in the PageLoad event
if (!IsPostBack)
txtName.Attributes.Add("readonly","readonly");
and you're done. Just don't forget to remove ReadOnly="true" or Enable="false" if your intent was to disable the control from editing just use the snippet above. Don't forget to remove Enable="false" if you put it on.
Another thing I ran into... If you're using an ASP.NET TextBox Control (for example), and it's READONLY or DISABLED, the postback won't catch the changed value.
Per my issue, I was changing the value of the control thru javascript and even though the browser rendered the change, on the postback, the control still retained the original value.
Seems a common problem too... javascript kicks off a custom ASCX calendar control and result is injected by javascript, into the textbox. Users shouldn't be allowed to directly modify textbox value...
string strDate = Request.Form["id_of_input_element"].ToString();
I ultimately used the above to um, "reset" the control, after the postback, to it's changed value!
The <input> textboxes won't save their state after postback. ASP.NET does not handle that for you.
If you put code in your Page_Load event to set the values of the ASP.NET textboxes, the values that were posted back will not be saved, because Page_Load happens after the child control states are restored in the ASP.NET page lifecycle. The values are already restored by ASP.NET, but you are overwriting their restored values.
The correct thing to do to fix #2 is to check Page.IsPostBack before loading your initial state, like this:
if ( !Page.IsPostBack )
{
// set the textbox initial states from the database
}
UPDATE:
There are two ways to solve problem #1. One thing you could do is to use the Request.Form[] collection to retrieve the posted back value manually, like this:
string strDate = Request.Form["id_of_input_element"].ToString();
The other thing you could do, and this is what I'd recommend if you can, is to change the <input> element to an ASP.NET textbox, and hook up any client-side Javascript events to that. Then ASP.NET will completely handle your postback.
i found this when looking for an answer to the same type of problem and now that i found my problem i thought it could help someone else putting it here.
in my case i had a tag <form> inside the <form> of my controls, so, if you didnt resolve your problem with above i sugest search for a <form> lost inside your <form>.
hope it helps for some cases.
If I get you're asking for right, I think you're trying to make those textboxes readonly. If so, I had this problem before and solved it by making the textboxes readonly using C# not ASP.NET, I just added lines like textboxName.Attributes.Add("readonly", "readonly"); in the Page_Load and it worked just fine. This solution I found here on Stackoverflow
instead of TextBoxPassword.Text=Password
use
TextBoxPassword.Attributes["value"]=Password
It seems that your viewstate is disabled. Enable the viewstate in Page directive.
Related
I have ASP.Net application that have multiple User Controls in the same page every one have its hidden field that holds a value, and every one have button that calls pop-up and through this value from hidden field to it.
The problem that when i try to access the hidden field and get the value inside , the program always get the last one (which created last).
How can i get the value of the inner hidden field in the current UserControl (Which i'm clicking the button from)?
Attempts:
var hdnRegion = "<%=hdnRegionId.ClientID%>";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
another one:
var currentControl = "<%=this.ClientID%>";
var hdnRegion = currentControl + "_" + "hdnRegionId";
var regionIdVal = $("#" + hdnRegion).val();
methodName(regionIdVal);
I also tried to call a property from code behind that returns the value and one that returns the whole control with no correct result.
Any suggestions would be appreciated...
Accourding to your comment under the question, your btnUpdate and hdnRegionId controls are in the same container (for instance in the same div) so try this:
$('input[id*="btnUpdate"]').click(function(){
var regionIdVal = $(this).parent().children('input[id*="hdnRegionId"]').val();
methodName(regionIdVal);
});
This is a JSFiddle Demo that simulate your HTML code that is rendered by ASP.NET.
I am taking over a project in which a client has some annoying issues.
They have a dropdown that autopostbacks on change to place the selected text into a t-sql query. Any value that has an apostrophe is causing an query error due to not being escaped
I do not have access to compiled code, but was hoping to write a quick band-aid fix to on selected changed, before posting replace an apostrophe to a double apostrophe to escape it as it goes into query.
I wrote a javscript ddl.change function that works at changing the text.
This however is not working even though the apostrophe does change into two. I was wondering if someone could help understand why.
I have two thoughts of scenarios causing the issue.
On autopostback, it triggers before javascript change function does, therefore passing the original value before javascript has a change to modify it.
The server side code only understands what it originally placed into the dropdown and therefore no matter how much I manipulate the client code, it will only see what it placed?
Can anyone confirm either of these scenarios?
Help would be appreciated!
EDIT: I REVERSE ENGINEERED THE CODE, YES ITS VERY UGLY (AND SQL INJECTABLE) BUT IS NOT MINE AND I CANNOT MODIFY IT
C# Code
protected void ddls_SelectedIndexChanged(object sender, EventArgs e)
{
if (this.ddls.SelectedIndex == 0)
{
this.pnlA.Visible = false;
}
else
{
this.pnlA.Visible = true;
string text = Common.GetSql("~/Sql/" + this._Conn + "/PropertyAddressReverseSearch.sql", false, true).Split(new char[]
{
Conversions.ToChar(this._Delimiter)
})[4];
text = string.Concat(new string[]
{
"SELECT * FROM (",
text,
") a WHERE StreetName='",
this.ddls.SelectedItem.Text,
"' "
});
this.Bind(this.ddla, text);
this.ddla.Items.Insert(0, new ListItem("I'm not sure of the house number...", Conversions.ToString(-1)));
this.ddla.Items.Insert(0, new ListItem("", Conversions.ToString(0)));
this.map.Visible = false;
}
}
Javscript + Control
<asp:dropdown runat="server" id="ddls" autopostback="true">
<script type="javascript/text">
$(document).ready(function() {
$("select[id$='adsearch_ddls']").change(function() {
var ddlsValue = $("select[id$='adsearch_ddls'] option:selected").text();
ddlsValue = ddlsValue.replace(/'/g,"\'\'");
$("select[id$='adsearch_ddls'] option:selected").text(ddlsValue);
return false;
});
});
</script>
You can not modify (or add/remove) the Select/dropdown list items client-side, and simply get the same server-side items, with ASP.NET Webforms when viewstate is enabled.
Unless you send back the modified items in another way, like for example in this answer where list items are copied to a hidden field:
function SaveList()
{
//Clear the hidden field
var hField = document.getElementById('<%= YourHiddenField.ClientID %>');
hField.value = '' ;
var selectedList = document.getElementById('<%= YourDropDownList.ClientID %>')
for(i = 0; i < selectedList.options.length; ++i)
{
hField.value = hField.value + ',' + selectedList.options[i].value;
}
That is, assuming by "On selected index change calls server side code" you mean a postback is triggered?
Disabling the ViewState will cause other problems (like SelectedIndexChanged not triggering, etc).
You could handle the selection change through your own (AJAX) postback. But the difference between server- and client-side list items would still remain.
I created a range validator and would like to trigger it once the submit button was clicked.
RangeValidator rv_tbAbsenceDay = new RangeValidator();
rv_tbAbsenceDay.ID = "rv_tbAbsenceDay" + tbAbsenceDay.ID;
rv_tbAbsenceDay.ControlToValidate = tbAbsenceDay.ID;
rv_tbAbsenceDay.EnableClientScript = true;
rv_tbAbsenceDay.Display = ValidatorDisplay.Dynamic;
rv_tbAbsenceDay.MinimumValue = DateTime.Now.AddMonths(-6).ToString("d");
rv_tbAbsenceDay.MaximumValue = DateTime.Now.ToString("d");
rv_tbAbsenceDay.ErrorMessage = "Date cannot be older than 6 months and not in the future.";
rv_tbAbsenceDay.SetFocusOnError = true;
plcMyStaff.Controls.Add(rv_tbAbsenceDay);
plcMyStaff is a placeholder.
<asp:PlaceHolder ID="plcMyStaff" runat="server"></asp:PlaceHolder>
How do I get hold of the created range validator to trigger it i.e. rv.validate(); ?
I have tried this:
protected void MarkAsSick_Command(Object sender, CommandEventArgs e)
{
DropDownList tempddlReason = (DropDownList)plcMyStaff.FindControl("ddlReason" + e.CommandArgument.ToString());
TextBox temptbAbsenceDay = (TextBox)plcMyStaff.FindControl("tbAbsenceDay" + e.CommandArgument.ToString());
TextBox temptbLastDayWorked = (TextBox)plcMyStaff.FindControl("tbLastDayWorked" + e.CommandArgument.ToString());
RangeValidator temprv_tbAbsenceDay = (RangeValidator)plcMyStaff.FindControl("rv_tbAbsenceDay" + e.CommandArgument.ToString());
temprv_tbAbsenceDay.validate();
...
Hope you can help me.
thanks,
Andy
First off to debug this I would suggest examining the plcMyStaff object in which you are adding the control to see if it does in fact contain the control you wish to access.
You should be able to retrieve it from the Page object that your webform inherits.
Page.FindControl();
// Or you can Iterate through each control to see what the control is called and test for the name you want
foreach (var control in Page.Controls)
{
}
I'm using a Textbox with an AutoCompleteExtender.
Enter the part number, click Find - it fills in the page.
I have a button on the page that reads the text of the textbox, uses that as a querystring parameter, and opens a new window.
Works great the first time. BUT
I close the 2nd window.
Add a new part number, click Find - it fills in the page with the new information correctly.
I click the button - and here's the PROBLEM -
It's holding the original part number when it opens the new window.
I've tried adding a second querystring parameter (datetime), and it still holds that same part number. I've also tried transferring the text to a hidden label, and reading it from there (thinking the autocompleteextender had something to do with it). No luck.
Here's the code for the button -
protected void btnViewIncidents_Click(object sender, EventArgs e)
{
try
{
string strDOT = txtXingList.Text;
DateTime DT = DateTime.Now;
btnViewIncidents.Attributes.Add("onclick","window.open('Incidents.aspx?DOT=" + strDOT + "&DT=" + DT + "'); return false;");
}
catch (Exception ex)
{
throw (ex);
}
}
and the code for the 2nd page retrieval of the parameters
string Crossing = Page.Request.QueryString["DOT"];
string DT = Page.Request.QueryString["DT"];
txtXingList.Text = Crossing;
Any suggestions/help is greatly appreciated! Thanks!
Is the txtXingList being populated somewhere else? If it does, check the code, it might be called before the button click event.
Some event are called before the button click.
Since your form is surely a method="post", then when you click the btnviewIncidents the query string will not change.
If the page load uses the query string to populate the txtXingList then when the button event will be called it will contain the wrong value.
The page needed to know absolutely that you wanted a popup form, even though it just opens a new tab. Worked like a charm.
try
{
string strDOT = txtXingList.Text;
DateTime DT = DateTime.Now;
string newWin = "window.open('../Application/AppsSB.aspx?DOT=" + strDOT + "&DT=" + DT + "');";
ClientScript.RegisterStartupScript
(this.GetType(), "pop", newWin, true);
}
catch (Exception ex)
{
throw (ex);
}
i'm having issues retreiving the values out of a dynamically created dropdownlist. all controls are created in the Page_Init section. the listitems are added at that time as well from an array of listitems. (the controls are named the same so should be accessable to the viewstate for appropriate setting.)
here is the function that attempts to retrieve the values:
protected void Eng98AssignmentComplete_Click(object sender, EventArgs e)
{
String myID = "0";
Page page = Page;
Control postbackControlInstance = null;
// handle the Button control postbacks
for (int i = 0; i < page.Request.Form.Keys.Count; i++)
{
postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]);
//Response.Write(page.Request.Form.Keys[i].ToString());
if (postbackControlInstance is System.Web.UI.WebControls.Button)
{
myID = Convert.ToString(
postbackControlInstance.ID.Replace("button_", ""));
}
}
String txtholder = "ctl00$ContentPlaceHolder$Eng098Instructors_" + myID;
Response.Write("MYID: " + myID + "<br/>");
DropDownList ddInstructorCheck = (DropDownList)Page.FindControl(txtholder);
Response.Write("Instructor Selected: "
+ ddInstructorCheck.SelectedValue + "<br/>");
}
here is the output I get, no matter which instructor was selected.....
MYID: 1_1
Instructor Selected: 0
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
the name of the control is correct (verified via view source)....
ideas?
You're going to a lot of work to build this fancy string:
ctl00$ContentPlaceHolder$Eng098Instructors_1_1
That is the client ID of your control, not the server id. This code is running on the server side, and so you need the server id. To get that control using the server id, you need to do this:
ContentPlaceHolder.FindControl("Eng08Instructors_1_1");
Notice I didn't look in the page, because your content place holder created a new naming container.
Also, the way your loop is set up the myID variable will always end up holding the last button in the Keys collection. Why even bother with the loop?
Based on your comments, a better way to find the id of the dropdownlist is like this:
string id = ((Control)sender).ID.Replace("button_", "Eng098Instructors_");
why not just save the control in an instance in your class so that you don't have to use FindControl?
Do you also re-create the controls during the postback? Dynamically generated/added controls must be re-created with every request, they are not automatically re-created.
Why don't you cast the sender? This should be the button that caused the postback:
string myId = "0";
Button btn = sender as Button;
if (btn != null)
myId = btn.ID
...
You need to perform something like this because the UniqueID property is the key in Request.Form.
List<Button> buttons = new List<Button>();
List<DropDownList> dropdowns = new List<DropDownList>();
foreach (Control c in Controls)
{
Button b = (c as Button);
if (b != null)
{
buttons.Add(b);
}
DropDownList d = (c as DropDownList);
if (d != null)
{
dropdowns.Add(d);
}
}
foreach (String key in Request.Form.Keys)
{
foreach (Button b in buttons)
{
if (b.UniqueID == key)
{
String id = b.ID.Replace("button_", "");
String unique_id = "ctl00$ContentPlaceHolder$Eng098Instructors_" + id;
Response.Write("MYID: " + id + "<br/>");
foreach (DropDownList d in dropdowns)
{
if (d.UniqueID == unique_id)
{
Response.Write("Instructor Selected: " + d.SelectedValue + "<br/>");
break;
}
}
}
}
}
I'm not sure why you are generating the control in code (you can still add items dynamically if you do), but the code that generates the controls would probably be a huge help here. I'm guessing you are not setting the list item value, and instead just setting the list item text. Try seeing what you get from the SelectedText field and post your control creation function.
EDIT:
In response to your comment on #Martin's post, you said "yes I recreate the controls in the Page_Init function each time the page is created (initial or postback)". Are you also setting the selected value when you create them?
You can also use controls on the page even if your data comes from a database, the controls themselves don't have to be dynamically generated.
How about this?
((Button)sender).Parent.FindControl(myid)
Edit:I misunderstood your question. But i think you should follow page lifecycle. it is common issue for dynamically created controls.
I did some research and here is some info about Dynamically Created Controls may help you...
I had 2 catches.... here's what they were.
1. I didn't clear the table I was adding to before re-creating the controls.
apparently my attention to detail was off yesterday, i'm pretty sure the ctlXX frontrunner of the control was some different number upon postback due to how I was recreating the controls.
2. I was assigning the same list to all the dropdownlist controls.
once I called the lookup upon each creation a dropdownlist control, all works well.
anyway for what it's worth....