I have a master page on which I have a dropdown of Language. I save dropdown's selected value in session. and want to check on page load that what's the value in session. But it gives exception because on page load, there is nothing in session.
Can anyone tell me what method should I call before page load in which I can set session to a default value?
Thanks in advance.
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Language"] = ddlLanguage.SelectedValue;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguage.SelectedValue = Session["Language"].ToString();
}
You could initialize your session variable to a default value inside the Page_Init event. So by the time the Page_Load event is fired, at least you would have a value to check against.
Alternatively, you could just check the Session variable for a null value in the Page_Load event & not try and use its value if indeed it is null.
For this second option, change your code to be something like:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ddlLanguage.SelectedValue = Session["Language"] == null ? "0" : Session["Language"].ToString();
}
Replace the zero in the true condition of the ternary operator with whatever default value you have in your dropdown list.
You have to check it before using it because when you are trying to get the value from the session it is null and not assigned any value yet.
if (Session["Language"] != null)
{
ddlLanguage.SelectedValue = Session["Language"].ToString();
}
No need to set default option in page init event, you can set language dropdown in page load event also like this ways :
Master page Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["culture"] != null)
ddlLanguage.SelectedValue = Session["culture"].ToString();
else
{
ddlLanguage.SelectedValue = "en-US";
Session["culture"] = "en-US";
}
}
}
protected void ddlLanguage_SelectedIndexChanged(object sender, EventArgs e)
{
Session["culture"] = ddlLanguage.SelectedValue;
}
=================
By this way I can preserve selected language in session and can use in whole application.
You could use Page_PreLoad event to set your session variable's value...
Related
From the selectedindexchanged event, my variable has a value, but when it reaches the btn_click() event, the variable no longer has a value. Why is that?
public partial class TestingDatapass
{
private string item = null;
private string itemprice = null;
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
//Both have a value here
item = item.SelectedValue;
itemprice = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
//no value here
totalprice = Convert.ToInt32(itemprice)*Convert.ToInt32(item);
MessageBox.Show(totalprice);
}
}
EDIT
And to answer the ? posed in comments, the order of occurrence is the selectedindexchange THEN the btn_click()
EDIT REGARDING View State
So then would this be a proper way to set up what I am trying to achieve?
public partial class TestingDatapass
{
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
ViewState["item"] = item.SelectedValue;
ViewState["itemprice"] = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(ViewState["item"])*Convert.ToInt32(ViewState["itemprice"]);
}
}
When a page is requested, ASP.NET creates an instance of TestingDatapass class and initialize itemprice,totalprice etc. fields. Now when you change your dropdown from client (which I assume looking at your item_selectedindexchanged method), Postback happens and it assign values you have mentioned in item_selectedindexchanged. Finally it destroys the instance, generates the html and sends it back to browser.
Now, when you press the button in your page then a new instance is created, your fields are re-initialized and you don't see the changed values in btn_click. This is how it works.
Thus if you want to preserve any data across postback, Consider using any State Management technique like ViewState, HiddenField etc.
Also, as a side note, MessageBox.Show is not available in ASP.NET.
Update:
I answered in the context of why it is not retaining the value in button click event, there are many ways to do it. But to answer your question, I don't see any reason to store the values in item_selectedindexchanged event as you are not doing anything there. You can directly access the dropdown selected values in button click handler like this:-
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(item.SelectedValue) *
Convert.ToInt32(item.SelectedItem.Text);
}
Also, please note it's item.SelectedItem.Text and not SelectedValue.Text.
I have a web app with a dropdown list. When a new index is selected I have to storing the value to a session variable, which is created on Session_Start event.
protected void Session_Start(object sender, EventArgs e)
{
Session.Add("testValue", "test");
}
On selectedindex changed event i'm setting the new value like this
Session["testValue"] = DropDownList.SelectedItem.Text;
I have a web service where I retrieve the value of the session variable like this:
[WebMethod(EnableSession = true)]
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
From a console app I connect to the web service and retrieve the value returned by getValue(), however the initial value is always being returned. any idea please?
The issue is because when the console app is run it seems that a new session is created. Using Application state using Application.Set and Application.Get solved the issue. Hopefully i will not have issues when the system will be used by multiple users.
Check whether the values of the items in your dropdown list are different.This is essential for your selected index changed event to be fired.
Here the values are not changed, You didn't change the values. So nothing expected
public string getValue()
{
var testVal = Session["testValue"].ToString();
return testVal.ToString();
}
The mistake is probably in dropdownlist
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["testValue] = dropdownlist1.SelectedItem.text;
}
}
And,
protected void dropdownlist1_SelectedIndexChanged(object sender, EventArgs e)
{
Session["testvalue"] = dropdownlist1.SelectedItem.text;
}
Also try with
System.Web.HttpContext.Current.Session["testvalue"]
in both parts
Hi I am trying to redirect to the previous page on button click but things are not going so well here is my code:
private string previousPage = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(previousPage);
}
When I first get directed to this page the previousPage variable stores the correct URL but after I click on the button for some reason previousPage value is change to the curent page url and i get sent back to the curent page.
What am I doing wrong here and how can I corect it?
EDIT
I wrapped the code like this:
if(!IsPostBack)
{
if( Request.UrlReferrer != null ) {
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
And I get redirected to a page that I did not create and has a link.On the page is written:
Object moved to here.
"here" is a link and when I cliked it I get sent back to the page I pressed the button
When you have a postback, the referrer is the page itself, so this is expected behaviour :-)
One solution would be to have something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack) Session["prev"] = Request.UrlReferrer.ToString();
if(Session["prev"] == null) {some code that disables the back button goes here!}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(Session["prev"] as string);
}
The reason why this answer works and the others posted so far do not, is that I am using Session["prev"] to remember the most recent valid referrer. So the trick is to 1) realise that when you have a postback the referer is url of the page itself (which the OP did) and 2) remember the last non-post referrer URL so that you can use it when the Back button is pressed.
You need to test for a postback. When you click the button the page is posted back to the server and the referrer becomes the page you are on and the value you want is overwritten.
private string previousPage = string.Empty;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
}
protected void BackButton_Click( object sender , EventArgs e )
{
Response.Redirect(previousPage);
}
you forgot put it in IsPostBack that y its working like this
if(!IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
code like this to work with it...
When you click on your button, the page load is executed before the click event, so it is resetting the value of your previousPage variable. You need to wrap it in a check to make sure it's not been posted back, like so:
if (!IsPostBack) {
previousPage = Request.UrlReferrer.ToString();
}
I am the last to answer but was first to comment
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
if( Request.UrlReferrer != null)
{
previousPage = Request.UrlReferrer.ToString();
CrossSideScriptingErrorCheck.Text = previousPage;
}
}
}
Can you please tell me what am I doing wrong here.
Why the Cookie data is not stored when I reload the page:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// it is always null !!!!
if (Response.Cookies["user_id"].Value != null)
{
//code never gets here
}
}
}
and this is the code for storing the cookie (after clicking a checkbox):
protected void CheckBoxRememberMe_Click(object sender, EventArgs e)
{
Response.Cookies["user_id"].Value = tbUserID.Text;
Response.Cookies["user_id"].Expires = DateTime.Now.AddDays(15);
}
So: I click on the checkbox, the value of tbUserID textbox is stored in the HttpCookie, then I reload the page (refresh) and the value is null.
Any idea ?
When checking for the cookie you want to be making a request rather than adding the cookie to the response.
if (Request.Cookies["user_id"].Value != null)
{
//code should get here
}
I am trying to pass data between two pages using Session State in ASP.NET. The data that needs to be passed is from a GridView's Cell. So, on SelectedIndexChanged event I'm storing the data like that:
protected void GridViewEmployees_SelectedIndexChanged(object sender, EventArgs e)
{
Session["Name"] =
this.GridViewEmployees.Rows[GridViewEmployees.SelectedIndex].DataItem;
}
And then, I want to use the Session's contents in another page. The code:
protected void Page_Load(object sender, EventArgs e)
{
string name = (string)(Session["Name"]);
string[] names = name.Split(' ');
this.EntityDataSourceNorthwind.Where =
"it.[FirstName] = \'" + names[0] +
"\' AND it.[lastName] = \'" + names[1] + "\'";
}
But I get a null reference exception. Also, I have set the Session initialization on the Page_Load event and there the Session is stored and everything works just fine. I mean:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Name"] == null)
{
Session["Name"] = "Andrew Fuller";
}
}
This is in the page which sends the information.
If you need more source or info, just write it down. It will be provided ASAP.
Thanks in advance!
This is actually not a problem with your Session. A row's DataItem is only available during the RowDataBound event. Set a break point in your GridViewEmployees_SelectedIndexChanged method, and check the value of the DataItem in your immediate window. It will be null.
The two most likely culprits are either - session state is disabled (EnableSessionState="false"), or cookies are disabled and you're not using cookieless sessions.