textbox text changes, querystring parameter doesn't - c#

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);
}

Related

Removing dynamically created HTML table rows - Life Cycle / Viewstate problem

so i have an HTML table with dynamically added rows and ASP.NET text boxes. I have the rows and controls re-instantiated on page_load if the viewstate[dataonpage] = true, and I'm declaring it as true in the method that adds the rows and controls. (I need them to persist on other postbacks)
The problem is that I'm now I've added a CLEAR button that removes all of the html rows (excluding the headers) when it's clicked, and for some reason on button click it gets an index error, or if using Try/Catch it only removes half of the rows (every other row). I believe the problem is something to do with that the viewstate[dataonpage] is still "true", and the data is being re-added on page load. If i add viewstate["dataonpage"] = "false" into the clear button method, the same happens but at least this way on the second click it removes the second half of the rows.
I understand this happens because the button event handler isn't fired until after the page_load which is why it doesn't work on the first click. But what I don't fully understand is why even without this my clear button code doesn't clear all of the rows in the first place.
Any help on understanding why it doesn't work, and a work around will be greatly appreciated!
protected void Page_Load(object sender, EventArgs e)
{
if (Convert.ToString(ViewState["DataOnPage"]) == "true")
{
Getmarketdata();
}
}
protected void Getdatabtn_Click(object sender, EventArgs e)
{
ViewState["DataOnPage"] = "true";
Getmarketdata();
}
Below is method that creates adds table rows and controls:
public void Getmarketdata()
{
String url = "https://api.rightmove.co.uk/api/rent/find?index=0&sortType=1&maxDaysSinceAdded=" + Dayssinceuploadtext.Text + "&locationIdentifier=OUTCODE%5e" + Outcodetext.Text + "&apiApplication=IPAD";
Response.Write(url);
using (var webclient = new WebClient())
{
String Rawjson = webclient.DownloadString(url);
ViewState["VSMarketDataJSONString"] = Rawjson;
dynamic dobj = JsonConvert.DeserializeObject<dynamic>(Rawjson);
int NoOfHouses = dobj["properties"].Count;
Response.Write("<br />" + NoOfHouses);
for (int i = 0; i < NoOfHouses; i++)
{
System.Web.UI.HtmlControls.HtmlTableRow tRow = new System.Web.UI.HtmlControls.HtmlTableRow();
GeneratorTable.Rows.Add(tRow);
String RMlink = String.Format("https://www.rightmove.co.uk/property-to-rent/property-" + dobj["properties"][i]["identifier"].ToString()) + ".html";
HyperLink hypLink = new HyperLink();
hypLink.Text = dobj["properties"][i]["identifier"].ToString();
hypLink.Target = "_blank";
hypLink.NavigateUrl = RMlink;
using (System.Web.UI.HtmlControls.HtmlTableCell tb1 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
tRow.Cells.Add(tb1);
tb1.Controls.Add(hypLink);
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb2 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbEPCe = new TextBox();
tRow.Cells.Add(tb2);
tb2.Controls.Add(tbEPCe);
String txtboxID = (("EPCETxtBox") + i);
tbEPCe.ID = txtboxID;
tbEPCe.Style.Add("background", "none"); tbEPCe.Style.Add("border", "1px solid black"); tbEPCe.Style.Add("border-radius", "2px");
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb3 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbEPCp = new TextBox();
tRow.Cells.Add(tb3);
tb3.Controls.Add(tbEPCp);
String txtboxID = (("EPCPTxtBox") + i);
tbEPCp.ID = txtboxID;
tbEPCp.Style.Add("background", "none"); tbEPCp.Style.Add("border", "1px solid black"); tbEPCp.Style.Add("border-radius", "2px");
}
using (System.Web.UI.HtmlControls.HtmlTableCell tb4 = new System.Web.UI.HtmlControls.HtmlTableCell())
{
TextBox tbBbl = new TextBox();
tRow.Cells.Add(tb4);
tb4.Controls.Add(tbBbl);
String txtboxID = (("BblTxtBox") + i);
tbBbl.ID = txtboxID;
tbBbl.Style.Add("background", "none"); tbBbl.Style.Add("border", "1px solid black"); tbBbl.Style.Add("border-radius", "2px");
}
}
}
}
Below is clear table rows method: (this is the one that isn't working)
public void ClearTableRows()
{
System.Web.UI.HtmlControls.HtmlTable Htmlgeneratortable = ((System.Web.UI.HtmlControls.HtmlTable)GeneratorTable);
int NoOfRows = Htmlgeneratortable.Rows.Count;
for (int j = 1; j < NoOfRows; j++)
{
try
{
Htmlgeneratortable.Rows.RemoveAt(j);
}
catch
{ }
}
}
I'm going to explain what's going on as you have the code written now; I don't have faith in my ability to provide an answer including the exact code changes to be made, so here is what is wrong with your current approach:
Your table, GeneratorTable exists for all clients. That doesn't mean every time someone navigates to your website a table is generated, it means that there is one table, and every client that logs in is getting that one table.
So if you add rows to it for one client, then send the table to another client, both clients will see the same table (with the rows added).
The problem is that emptying out a table is logic that has nothing to do with your back-end server. There's no reason for your server to be handling emptying a table, your server should only handle page navigations and AJAX calls pretty much, it shouldn't be changing how the webpage looks, because the server can only respond to each client one time.
What's the point in responding to a client with GeneratorTable and then updating GeneratorTable on the server? The client will never see the updates made to the table unless they're resent from the server.
You stated that you are new to this and need to learn about JS and client-side, this exercise should serve as an example of why you need to put certain code on the front-end and some code on the back-end, as there isn't really an elegeant way to do what you're looking to do with just the server.

Passing Variable from one WPF Window to Another (C#)

I really feel bad for having to ask this. The answer should probably be obvious; however, I have searched here and on Google to no avail.
I am quite new to WPF. With Windows Forms, I recall it was quite easy to pass data between Windows, but I cannot figure it out with my WPF application.
I am simply building an application for myself that will allow me to access and insert data in a MySQL database. When the button I have added to view all the records in a table is clicked, I want a new window to open. This window will simply display all the data; the table will be selected in MainWindow.
The problem I have is this: I need someway for the secondary window (View) to know which table was selected. I will probably use a ListBox control for table selection, but at the end of the day it really does not matter. Eventually, the value will be stored as a string in a variable. I need the View window to be able to access this string so it knows which table to query. In example:
// Main Window
private void viewButton_Click(object sender, RoutedEventArgs e)
{
var table = "DS";
View viewWindow = new View();
viewWindow.Show();
}
// View Window
private void windowLoad(object sender, RoutedEventArgs e)
{
DatabaseConnection myConnection = new DatabaseConnection();
List<string>[] result = myConnection.Select(table);
text.Text = MainWindow.test + (result[0][0] + " " + result[1][0] + " " + result[2][0] + " " + result[3][0]);
}
All I need to do is to pass the value of table (which will vary in the final application based on user input), to View. For example, I need it so that in the above code, the following would be executed:
List<string>[] result = myConnection.Select("DS");
I feel like this should be obvious and easy, but I am not sure how to accomplish this. I would sincerely appreciate any help.
You can pass a variable through constructor, like this
public View(string table)
{
this.table = table;
}
And when you initialize your window:
var table = "DS";
View viewWindow = new View(table);
viewWindow.Show();

Why are my list controls being cleared after being populated in WizardStep0 in an ASP.NET Wizard control?

I'm using a Wizard control in an ASP.NET application. In several of the WizardSteps, I'm populating a DropDownList and a CheckBoxList in the Activate event of the step. This works correctly in all steps except WizardStep0. What's happening is that the code is running to populate the lists, but once rendering is complete on WizardStep0, the list controls are empty, as if they've been cleared.
Here's the WizardStep0_Activate method:
protected void WizardStep0_Activate(object sender, EventArgs e)
{
//Initialize dropdowns
PopulateRelationList(ddlRelation);
PopulateGuardianshipTypeList();
} //end method WizardStep0_Activate
Here are the two methods called in WizardStep0_Activate (the method BindSelectionListLocalized works elsewhere, so I know the problem isn't there):
protected void PopulateRelationList(DropDownList ddlist)
{
//First, clear the list
ddlist.Items.Clear();
string valueField = "RelationID";
string textField = "Relation";
string query = "SELECT CONVERT(nvarchar(2), RelationID) AS RelationID, Relation FROM tlkRelation WHERE Lang ='" + lang + "'";
DBFunctions.BindSelectionListLocalized(query, textField, valueField, ddlist, GetGlobalResourceObject("LocalizedText", "selectDDL").ToString());
} //end method PopulateRelationList
protected void PopulateGuardianshipTypeList()
{
//First, clear the list
cblGuardianshipType.Items.Clear();
string valueField = "GuardianshipType";
string textField = "TypeDescr";
string query = "SELECT GuardianshipType, TypeDescr FROM tlkGuardianshipTypes WHERE Lang = '" + lang + "'";
DBFunctions.BindSelectionListLocalized(query, textField, valueField, cblGuardianshipType, null);
}
Here's what I'm getting (just the two list controls mentioned above) - the "Type of Guardianship Requested" should have a CheckBoxList with four items next to it; the "Relation to Client" DropDownList should have several choices:
The most important information is that the same code works correctly in the Activate events for all subsequent WizardSteps, just not for WizardStep0. When I run this in the debugger, WizardStep0_Activate is firing, and the methods to populate the list controls are running; the offending controls are somehow being cleared afterwards, when the page is rendered.

How to return value back to parent page from window.ShowModelDialog?

I'm facing some issue with returning value back to the parent page.
Please kindly help.
I have a gridview that allow users to add new record at the row, but users also can click on the Search button on the row, and I will show a pop up with the below code.
TextBox txtCarNo = gvLookup.FooterRow.FindControl("txtNo") as TextBox;
System.Text.StringBuilder s = new System.Text.StringBuilder();
s.Append("<script language='javascript' id='SearchResult'> " );
s.Append("var WinSettings = 'dialogHeight:400px ; dialogWidth: 550px ;center: Yes ;resizable: No;status: no'; ");
s.Append("javascript: window.showModalDialog('Search.aspx?no=" + txtNo.Text.Trim().ToUpper() + "','',WinSettings); ");
s.Append("</script > ");
if ((!ClientScript.IsStartupScriptRegistered("SearchResult")))
{
ClientScript.RegisterStartupScript(this.GetType(), "SearchResult", s.ToString());
}
At the child page, there will be another gridview that shows the search result, and users can click on one of the row to return the number back to the parent page.
I thought of using Session to pass the value back, but when showing the ShowModalDialog, the code at the parent page already went through, meaning Session won't work on this scenario.
Please advise how do I return a value to the parent page.
Appreciate very much.
Example from Wrox
When you call showModalDialog you do this:
var oReturnValue = showModalDialog(....);
Within showModalDialog, assuming your textboxes have IDs of "txtForename" and "txtSurname":
<body onbeforeunload="terminate();">
function terminate()
{
var o = new Object();
o.forename = document.getElementById("txtForename").value;
o.surname = document.getElementById("txtSurname").value;
window.returnValue = o;
}
Then continuing in your main window:
alert(oReturnValue.forename + "\n" + oReturnValue.surname);

textboxes lose value on postback

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.

Categories

Resources