I have the following code that opens a hyperlink in a different frame from code behind using the function ClientScript.RegisterStartupScript. The hyperlink was priory retrieved from a database and assigned to a label.
public void OpenWindow()
{
Formview_CurrentSelectedProcess.DataBind();
string url = (Formview_CurrentSelectedProcess.FindControl("LabelLink") as Label).Text;
string s = "window.open('" + url + "', 'main');";
Test.Text = s;
ClientScript.RegisterStartupScript(this.GetType(), "script", s, true);
}
This works perfect. Then I implemented a Querystring on that page. The Request Parameter is passed correctly and the hyperlink is opened on Pageload the way I expected. BUT: the next time this method is called, the hyperlink that will be opened, is the one belonging to the record specified in the Querystring Parameter. I placed a label inside to check if the correct parameter 's' is passed to ClientScript.RegisterStartupScript() and it is!!!
The mistake occurs with that function in case that the page had been loaded with a Querystring Parameter (eg.aspx?ID=324) Loading that same page without that parameter works perfect.
What happens? Why is ClientScript.RegisterStartupScript returning the old result, although it's input parameter has changed?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
PopulateRootLevel();
string GetID = Request.QueryString["ID"];
if (String.IsNullOrEmpty(GetID))
{
}
else
{
InputNodeToOpen.Text = GetID;
ButtonClick_transmit(button1, EventArgs.Empty);
InputNodeToOpen.Text ="";
IDNodesToBeOpened.Text = "";
}
}
Any hints on that?
Martin
OK. Found the mistake:
After placing all actions in the page_load method inside separate brackets it works. I thought they were already assigned to a no-post-back situation; but they were NOT. The brackets are needed. So it must be:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
PopulateRootLevel();
string GetStructure = Request.QueryString["Structure"];
if (String.IsNullOrEmpty(GetStructure))
{
}
else
{
InputNodeToOpen.Text = GetStructure;
ButtonClick_transmit(button1, EventArgs.Empty);
InputNodeToOpen.Text = "";
IDNodesToBeOpened.Text = "";
}
}
}
Related
I have a form with a lot of textboxes, dropdown menus and so on.
I use this form for entering NEW data but I also want to use the same page to CHANGE data. But then I have to fill the data with the information of the customer to be changed.
Now in Page_Load I have
protected void Page_Load(object sender, EventArgs e)
{
Master.PageTitle(PageTitles.UpdateAdd);
NameValueCollection nvc = Request.Form;
if (nvc.Count == 2 && nvc["ThisIsAnUpdate"] == "1")
{
// Ladies and gentlemen, we have an update. Do the work.
ThisIsAnUpdate.Value = "1";
DetailedAddressEntity myCustomer = new RetreiveInformation().FetchDetailedInformation(nvc["ID"]);
SetupEdit(myCustomer);
}
}
Then in SetupEdit I do this:
protected void SetupEdit(DetailedAddressEntity dae)
{
FirstName.Text = dae.aFirstName;
LastName.Text = dae.aLastName;
SubscriberNumber.Text = dae.aSubscriberNumber;
... and so on...
}
FirstName, LastName and SubscriberNumber never changes. They work perfectly when I use the page to create a new Customer since then I do postback to fill these textboxes, but when I try to access them when the page loads ... nothing.
I know the code in SetupEdit is actually run, but after the page is already drawn in my browser. I tried to force a postback, but that didn't work either.
Helps?
More explanation: Page_Load first set's the title of the page through the main page, since I do this without trouble I assumed I would be able to fill the textboxes too.
DetailedAddressEntity myCusomter is just a gazillion variables fetched from the DB.
I use the fetched information to fill the textboxes, but - alas - no info in them.
More info:
I moved the database call to SetupEdit and created a button on the page and called that function just to see if the function was broken. It works perfectly. It fetches all the info and fills up my textboxes perfectly.
But not if I call the same from Page_Load.
protected void SetupEdit(string ID)
{
DetailedAddressEntity dae = new RetreiveInformation().FetchDetailedInformation(ID);
FirstName.Text = dae.aFirstName;
LastName.Text = dae.aLastName;
SubscriberNumber.Text = dae.aSubscriberNumber;
... and so on...
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
Master.PageTitle(PageTitles.UpdateAdd);
NameValueCollection nvc = Request.Form;
if (nvc.Count == 2 && nvc["ThisIsAnUpdate"] == "1")
{
// Ladies and gentlemen, we have an update. Do the work.
ThisIsAnUpdate.Value = "1";
DetailedAddressEntity myCustomer = new RetreiveInformation().FetchDetailedInformation(nvc["ID"]);
SetupEdit(myCustomer);
}
}
}
I have a web page which is contained a Data Filter and a report.The Data Filter is a user control. The report is loaded inside the main page so totally i have two pages. one user control and one web page.
Now i am going to gather the data by clicking a button inside the user control then i can use it to filter the table, but it seems that during the post back it goes first to the Page_Load method of the main, not the user control so the report is constructed before filtering.The BtnPreviewReport_Click must be executed earlier than the page_Load.
What should i do ?
User control
protected void BtnPreviewReport_Click(object sender, EventArgs e)
{
Date = Year.Text + "/" + Month.Text + "/" + Day.Text;
}
Main Page
protected void Page_Load(object sender, EventArgs e)
{
string date = UserControls1.Date;
Response.Write(date);
}
Output : Nothing
I am not sure why the ButtonClick event should be run earlier than page load.
But here's a simple way to solve your question:
private bool isPageLoaded = false;
private bool isButtonClicked = false;
private void ButtonClick()
{
isButtonClicked = true;
doTheFirstThing();
if( isPageLoaded )
{
doTheSecondThing();
}
}
private void PageLoad()
{
isPageLoaded = true;
if( isButtonClicked )
{
doTheSecondThing();
}
// else let the button click handle the SecondThing()
}
I'm wondering what is my issue on passing a variable from page to page using asp.net session.
I've stripped the code down to just one text box to see whats going on. I'm just trying to take the value of a text box and display it on a confirmation page. When the button is clicked it transfers me to the second page but there label is blank. Yes my post back url is pointing to the second page.
Here is the button click:
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
}
Here is the page load of the second page:
protected void Page_Load(object sender, EventArgs e)
{
lblName.Text = (string)(Session["name"]);
}
Unless I've been looking at this to long and missed something. I've already read "How to: Read Values from Session State" from MSDN.
You say that you've set the PostBackUrl to your second page. If you're going to do it that way, you need to use Page.PreviousPage to get access to your textbox. But this is the easiest way:
Firstly, leave the PostBackUrl alone. Setting the PostBackUrl to your second page means that you're telling the SECOND PAGE to handle your button click, not the first page. Hence, your session variable never gets set, and is null when you try to pull it.
This should work for ya.
And yes, you can also do this with a QueryString, but if its something that you don't want the user to see/edit, then a Session variable is better.
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session["name"] = name;
Response.Redirect("PageTwo.aspx");
}
Then in the second page (You don't REALLY need the ToString()):
protected void Page_Load(object sender, EventArgs e)
{
if (Session["name"] != null)
{
lblName.Text = Session["name"].ToString();
}
}
EDIT -- Make sure that your button click actually gets fired. Someone can correct me wrong on this, as I do most of my work in VB.NET, not C#. But if you don't specify the OnClick value, your function won't get called.
<asp:Button ID="Button1" runat="server" Text="Click Me!" OnClick="submit_Click" />
The code you have posted looks fine, so your problem is probably with setup.
Check this link ASP.NET Session State Overview and pay particular attention to the sections on Cookieless SessionIDs and Configuring Session State.
I don't think you added the session. This is how I have done mine.
First Page
protected void btnView_Click(object sender, EventArgs e)
{
foreach (ListItem li in lbxCheckDates.Items)
{
if (li.Selected == true)
{
lblMessage.Text = "";
string checkDate = lbxCheckDates.SelectedItem.Text;
Session.Add("CheckDates", checkDate);
Page.ClientScript.RegisterStartupScript(
this.GetType(), "OpenWindow", "window.open('Paystub.aspx','_newtab');", true);
}
}
}
Second Page
protected void Page_Load(object sender, EventArgs e)
{
string checkDate = (string)(Session["CheckDates"]);
//I use checkDate in sql to populate a report viewer
}
So with yours, I think you need..
protected void submit_Click(object sender, EventArgs e)
{
string name = txtFirstName.Text.Trim();
Session.Add("Name", name);
}
I think what you have in the second page should work, but if it doesn't, add ToString() to it like..
lblName.Text = (string)(Session["name"]).ToString();
Let me know if this helps!
Are you doing a redirect after setting the session variable on the first page, if so you it will not work correctly (unless you know the trick). Checkout this article on making it work. Basically, the way to make this work is to the overload redirect method.
Response.Redirect("~/newpage.aspx", false);
The false parameter prevents .net from terminate processing on the existing page (that actually writes out the session state)
For Second Page
protected void Page_Load(object sender, EventArgs e)
{
if (Session["value"] != null)
{
Label1.Text = Session["value"].ToString();
}
else
{
Label1.Text = "Sorry,Please enter the value ";
}
}
You can use Server.Transfer() instead of Response.Redirect()
For first page, use this:
protected void Button1_Click(object sender, EventArgs e)
{
string value = TextBox1.Text;
Session["value"] = value;
Response.Redirect("~/Sessionpage.aspx");
}
I am having trouble getting the values of public variables file and desc set on the RowEditing method.
I have put a break-point at the end of the RowEditing and i can see that the file and desc values are being set, but when i click on Update these values on RowUpdating are being set back to "".
The gridDok.Rows[e.RowIndex].Cells[4].Text is also being set to "" and i get the ArgumentExceprion:
String cannot be of zero length.
Parameter name: oldValue
Does anyone have a suggestion?
Here is the code of the methods:
protected void gridDok_RowEditing(object sender, GridViewEditEventArgs e)
{
file = gridDok.Rows[e.NewEditIndex].Cells[5].Text;
desc = gridDok.Rows[e.NewEditIndex].Cells[4].Text;
}
protected void gridDok_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string file1 = file.Replace(desc, gridDok.Rows[e.RowIndex].Cells[4].Text);
File.Move("~/" + file, "~/" + file1);
}
Thanks in advance.
Yes, global variables are not retained across postbacks - store them via:
Session["file"] = gridDok.Rows[e.NewEditIndex].Cells[5].Text;
and retrieve them via:
var file = Session["file"] as string;
if (file != null) { .. }
HTH.
public void Submit1_Click(Object sender, EventArgs E)
{
string strheadlinesid1 = string.Empty;
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
{
strheadlinesid1 = Request.QueryString["folder"].ToString();
}
}
string URL = "view4.aspx?value="+strheadlinesid1;
Response.Redirect(URL);
}
This is a function I'm using but when I pass strheadlinesid1, "value" variable in URL is getting nothing.Why Is it happening.Is there any wrong in this approach.
On the button click, the page will be in the postback state and your condition will be false if (!IsPostBack) so it will not enter into the block and hence the value will not be assigned to strheadlinesid1
this block
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
{
strheadlinesid1 = Request.QueryString["folder"].ToString();
}
}
should be
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
{
strheadlinesid1 = Request.QueryString["folder"].ToString();
}
A button click is a postback so strheadlinesid1 will not be assigned to and will be empty.
You need to remove the check for IsPostback, since button click events will usually be executed as postback events.
public void Submit1_Click(Object sender, EventArgs E)
{
string strheadlinesid1 = string.Empty;
if (!string.IsNullOrEmpty(Convert.ToString(Request.QueryString["folder"].ToString())))
{
strheadlinesid1 = Request.QueryString["folder"].ToString();
}
string URL = "view4.aspx?value="+strheadlinesid1;
Response.Redirect(URL);
}
Because Button click is a postback and the code to read "folder" query string doesn't execute if it is a postback?
So the value of "value" is always empty.
Remove the check for !IsPostback if that is what you wanted.