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.
Related
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
I am trying to save the dropdown list selected value in a glbal variable .. I have lots of country on the dropdown list , whan I choose one of them and press a button :
protected void Button1_Click(object sender, EventArgs e)
{
Button2.Enabled = true;
Button2.Visible = true;
DropDownList1.Visible = true;
DropDownList9.Items.Clear();
if (!Class1.Search_Continent.Equals("-"))
{
SqlConnection conn1 = new SqlConnection(#"Data Source=AK-PC\MSSQLSERVER1;Initial Catalog=DB;Integrated Security=True");
conn1.Open();
SqlCommand cmd1 = new SqlCommand("Select Country_name FROM Country WHERE Continent_name='" + DropDownList1.SelectedValue + "'", conn1);
SqlDataReader dr1;
dr1 = cmd1.ExecuteReader();
while (dr1.Read())
{ DropDownList9.Items.Add(dr1["Country_name"].ToString() + "\n"); }
dr1.Close();
conn1.Close();
}
protected void Button2_Click(object sender, EventArgs e)
{
// Redirect to Country page
Class1.CountryName = DropDownList9.SelectedValue.ToString();
Response.Redirect("Country.aspx", true);
}
it doesnt take the selected value ! it always take the first value of the dropdown list !
Please help me !
You are probably re-binding the DropDownList9 on postback and losing the SelectedValue.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
//bind data
}
}
it always take the first value of the dropdown list
This is very common in web forms if you're populating the data incorrectly. Where are you populating the drop down list? I'm going to guess that you're doing it in Page_Load. I'm also going to guess that you don't have it wrapped in something like if (!IsPostBack). If you put a debugging breakpoint in Page_Load you'll find that it's called in the post-back before Button2_Click is called.
Keep in mind that HTTP is stateless. This means that the entire server-side page object needs to be constructed on each request to the server. Page_Load is part of that construction, and it happens before event handlers do. So what's likely happening is:
User requests initial page.
You populate the drop down list with data.
You display the page to the user.
User selects an option and clicks a button, making a post-back request.
You clobber and re-populate the drop down list, returning it to a default state.
You try to get the selected value, which is now gone.
The most common solution to this problem is to use the aforementioned conditional in Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
// some initial logic
if (!IsPostBack)
{
// stuff that should only happen when the page first loads
// for example, populating controls from the database
}
// any other logic, etc.
}
The values for the controls shouldn't need to be re-populated with each postback because things like viewstate should keep the necessary data available. (Though if you mess with that at all then you might need to tinker some more.)
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...
i want to pass a string value from one page to another.Also i have some text boxes and the values entered in it needs to be passed to a new page.How do i do it?
I have a string S
String S = Editor1.Content.ToString();
i want to pass value in string S onto a new page i.e Default2.aspx how can i do this in ASP.net C#
You can achieve it using Session or by QueryString
By Session
In your first page:
String S = Editor1.Content.ToString();
Session["Editor"] = S;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String editor = String.Empty;
if(!String.IsNullOrEmpty(Session["Editor"].ToString()))
{
editor = Session["Editor"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
// or other events
private void button1_Click(object sender, EventArgs e)
{
String S = Editor1.Content.ToString();
Response.Redirect("SecondPage.aspx?editor" + S)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string editor = Request.QueryString["editor"].ToString();
// do Something();
}
Depends on what the value is. If it is just a parameter and is ok to be viewed by the user then it can be passed through QueryString.
e.g.
Response.Redirect("Default2.aspx?s=value")
And then accessed from the Default2 page like
string s = Request.QueryString["s"];
If it needs to be more secure then consider using session, but I wouldn't recommend using the Session excessively as it can have issues, especially if you are storing the session InProc which is ASP.NET default.
You can have a state server or database but, it might be better to have your own database based session based on the authenticated user, and have it cached in the website if need be.
Use Session["content"]=Editor1.Content.ToString() in page1...
in page2 use...string s = Session["content"]
I have some trouble understanding this one so here it is.
I'm trying to set a cookie and display the value on the page using ASP.NET + C#.
here's my code:
protected void lbChangeToSmall_Click(object sender, EventArgs e)
{
Response.Cookies["fontSize"].Value = "small";
}
and
<asp:LinkButton runat="server" id="lbChangeToSmall" Text="A" CssClass="txt-sm" OnClick="lbChangeToSmall_Click"></asp:LinkButton>
And finally
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Response.Write( Request.Cookies["fontSize"].Value);
}
}
When I click on the button, nothing is displayed on the page, but the cookie is actually set. If I refresh the page, the cookie displays.
So it seems that the cookie is set correctly but the application is not able to read it right away.
I tried to get rid of the if(postBack):
protected void Page_Load(object sender, EventArgs e)
{
Response.Write( Request.Cookies["virgilFontSize"].Value);
}
but it didn't change a thing.
What am I doing wrong?
Thanks!
The lblChangeToSmall_Click event is fired after the Page_Load event. Therefore the cookie write won't be available on the Request until the subsequent postback.
It will be avaialable on the client immediately though.
The first time, the request has no cookies (yet); it will only have them the second time around, after the response has set them. So your code has to deal with the possibility that Request.Cookies just may not have a "fontSize" entry, and provide the proper default when that is the case. For example:
HttpCookie cookie = Request.Cookies.Get("fontSize");
// Check if cookie exists in the current request.
if (cookie == null)
{
Response.Write( "Defaulting to 'small'.");
}
else
{
Response.Write( Request.Cookies["fontSize"].Value);
)