Defining and adding value to variable from session-variable - c#

I'm trying to make a script that checks, if a user has the right age before joining a team. If the user age doesn't match the team age, the script should stop at this page, and require the user to click the button "BackToLastPageBtn" go back to the previous page, which uses a variable called "BackToLastPage", which gets its value from 'Session["currentUrl"]', before it is reset at Page_load.
The problem is, that it tells me the value is null, when clicking the button.
I don't know why it is null, when i add the value to "BackToLastPage", BEFORE resetting Session["currentUrl"]. I hope someone can tell me, and guide me in the right direction.
The CodeBehind - script
public partial class JoinTeam : System.Web.UI.Page
{
//Defining Go back variable
private string BackToLastPage;
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Adding value to go back variable from sessionurl
BackToLastPage = (string)Session["CurrentUrl"];
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
if (ClassSheet.CheckIfUserAgeMatchTeamAge(BrugerId, TeamId))
{
ClassSheet.JoinATeam(BrugerId, TeamId);
if (BackToLastPage != null)
{
//Uses the new savedUrl variable to go back to last page.
Response.Redirect(BackToLastPage);
}
else
{
Response.Redirect("Default.aspx");
}
}
else
{
AgeNotOk.Text = "Du har ikke den rigtige alder til dette hold";
}
}
else
{
//Not saving last page. Need to find solution.
Response.Redirect("Login.aspx");
}
}
//NOT WORKING...
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//Go back button
//Response.Write(BackToLastPage);
Response.Redirect(BackToLastPage);
}
}

Since you are setting session["CurrentURL"] to null in page_load. When the event is fired it no longer exists. Below is code that i got it working. I had to cut some of your code out since i dont have the definition of all your classes. Private properties do not persist through postbacks. If you wanted it to work the way you have it, you should save the previoius url in a hidden field on the page itself.
Page One:
protected void Page_Load(object sender, EventArgs e)
{
Session["CurrentUrl"] = Request.Url.ToString();
Response.Redirect("~/SecondPage.aspx");
}
Page Two:
private string BackToLastPage { get { return (Session["CurrentUrl"] == null) ? "" : Session["CurrentUrl"].ToString(); } }
protected void Page_Load(object sender, EventArgs e)
{
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
if (Session["brugerId"] != null)
{
//CUT CODE OUT DONT HAVE YOUR DEFINITIONS
Response.Write("brugerid was not null");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
//YOU SHOULD SET THE CURRENT URL TO NULL HERE.
string tempUrl = BackToLastPage;
Session["CurrentUrl"] = null;
Response.Redirect(tempUrl);
}
You can also try this, Store the return url in a hiddenfield and only set it if it is not a page postback:
Markup HTML:
<form id="form1" runat="server">
<div>
<asp:Button ID="btnOne" runat="server" OnClick="BackToLastPageBtn_Click" Text="Button One" />
<asp:HiddenField ID="hfPreviousUrl" runat="server" />
</div>
</form>
Code Behind:
private string BackToLastPage //THIS WILL NOW PERSIST POSTBACKS
{
get { return hfPreviousUrl.Value; }
set { hfPreviousUrl.Value = value;}
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)//THIS PREVENTS THE VALUE FROM BEING RESET ON BUTTON CLICK
BackToLastPage = (string)Session["CurrentUrl"];
int BrugerId = Convert.ToInt32(Session["BrugerId"]);
int TeamId = Convert.ToInt32(Request.QueryString["HoldId"]);
//Resets sessionurl.
Session["CurrentUrl"] = null;
if (Session["brugerId"] != null)
{
Response.Write("brugerID was not null");
}
else
{
//REMOVED FOR TEST PURPOSES
//Response.Redirect("Login.aspx");
}
}
protected void BackToLastPageBtn_Click(object sender, EventArgs e)
{
Response.Redirect(BackToLastPage);
}

Related

dropdown list goes back to first value after selected index changes

I have a drop down list with a button event that should send it's value for a textbox.But,even if I choose a value that is not the first one in the DDL,it only sends the value of the first item in the DDL. I was told to add the !IsPostBack in the page load,but it didn't help.
Codes:
protected void Page_Load(object sender, EventArgs e)
{
string testeddl;
codProfessor = Request.QueryString["id"];
if (db.conecta())
{
ddlTeste.Items.Clear();
ddlTesteAltDel.Items.Clear();
ddlQuestoes.Items.Clear();
listaX = db.retornaTestes(codProfessor);
for (int i = 0; i < listaX.Count; i++)
{
testeddl = listaX[i].nometeste;
ddlTesteAltDel.Items.Add(testeddl);
}
protected void btnBuscarTeste_Click(object sender, EventArgs e)
{
if (db.conecta())
{
int posic = ddlTesteAltDel.SelectedIndex;
txtNomeTeste.Text = listaX[posic].nometeste;
ddlaltdelTeste.Text = listaX[posic].materiateste;
}
}
}
}
In Page_Load, just need to indicate:
if(!IsPostBack()
{
// rest of the code.
}

Page_Load run Button_Click

I have a web-part in SharePoint 2013 which adds the new items from excel. The web-part contains upload control, buttons and textbox. I choose the document from upload control and click the button to load items in SP, if it was successfull I see "Successfull" in textbox or "Not successfull" in another way.
My problem: if i refresh page with web-part, textbox still contains the old text, but i want to see it empty after every refresh.
I try to use Page.IsPostBack, but I think I didn't properly use it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
textbox1.Text = "";
}
protected void btn3_Click(object sender, EventArgs e)
{
if (!Page.IsPostBack)
return;
if(!upload.HasFile)
{
textbox1.Text += "You didn't choose an Excel file";
return;
}
...
}
<asp:Button ID="btn3" runat="server" OnClick="btn3_Click" Text="Add Items" />
In such case, you can implement a special code block to detect browser refresh as
private bool refreshState;
private bool isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
refreshState = bool.Parse(AllStates[1].ToString());
if (Session["ISREFRESH"] != null && Session["ISREFRESH"] != "")
isRefresh = (refreshState == (bool)Session["ISREFRESH"]);
}
protected override object SaveViewState()
{
Session["ISREFRESH"] = refreshState;
object[] AllStates = new object[3];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(refreshState);
return AllStates;
}
In the button click you can do it as
protected void btn3_Click(object sender, EventArgs e)
{
if (isRefresh == false)
{
Insert Code here
}
}

How to override a session

I have a question can I overwrite a session that I allredy have set (I set the the user specific department)
Session:
int depId = user.HtDepartments.FirstOrDefault().DepartmentId;
Session["DepId"] = depId;
I want to override this id that I saved in the session with a new "id" that the user selectes out of the RadComboBox.
So when the user is coming back to this page not his "pre selected" department is selected , selected is the new department that he slected before
My code so far:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.Page.IsPostBack)
{
this.parameterDepId = this.Request["depId"];
if (string.IsNullOrEmpty(parameterDepId))
{
parameterDepId = Session["depId"].ToString();
}
this.LoadDE(parameterDepId);
this.UserGrid.DataBind();
}
}
Loading the session
Here how I load my department
protected void LoadDE(string depId)
{
IEnumerable<HtDepartment> departments = null;
if (this.selectedBu != null)
{
departments = this.selectedBu.HtDepartments;
}
this.rcbDepartments.DataTextField = "Name";
this.rcbDepartments.DataValueField = "DepartmentId";
this.rcbDepartments.DataSource = departments;
this.rcbDepartments.DataBind();
this.rcbDepartments.Items.Insert(0, new RadComboBoxItem("-All-"));
if (depId != null)
{
int index = this.rcbDepartments.Items.IndexOf(this.rcbDepartments.Items.Where(i => i.Value == depId).SingleOrDefault());
if (index > -1)
{
this.rcbDepartments.Items[index].Selected = true;
this.selectedDepartment = departments.Where(i => i.DepartmentId == int.Parse(depId)).SingleOrDefault();
}
}
}
protected void rcbDepatments_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
{
if (this.rcbDepartments.Items.Count > 1 && this.rcbDepartments.SelectedIndex > 0)
{
this.selectedDepartment = HtDepartment.GetById(int.Parse(e.Value));
parameterDepId = this.selectedDepartment.ToString();
}
else
{
this.selectedDepartment = null;
}
this.dataSourceFilterChanged();
}
A resume of my question:
How and where should I override my session in the load method or in SelectedIndexChanged ?
It makes sense to check for the saved variable when loading a page, as the user won't be able to interact with the controls until this method has completed.
private void OnLoad(object sender, EventArgs e)
{
this.parameterDepId = this.Request["depId"];
}
But to override it with a new value you simply set a new value. Then the next time you loaded the page this newly set value would be returned in the OnLoad method.
private void MyControl_SelectedIndexChanged(object sender, EventArgs e)
{
Session["DepId"] = MyControl.SelectedValue;
}
I'm finding your question a bit unclear but hopefully this answers the main point of it and helps with your code logic.

how to assign value for drop down select item c#

i need to assign value for selected value drop down in aspx for example
dropdownlist items
<asp:DropDownList ID="DropDownList1" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>1</asp:ListItem>
<asp:ListItem>2</asp:ListItem>
<asp:ListItem>3</asp:ListItem>
</asp:DropDownList>
<asp:DropDownList ID="DropDownList2" runat="server" OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged"
AutoPostBack="True">
<asp:ListItem>a</asp:ListItem>
<asp:ListItem>b</asp:ListItem>
<asp:ListItem>c</asp:ListItem>
</asp:DropDownList>
if user select any item in dropdownlist1 it should increment value 2 then
if user select any item in dropdownlist2 it should increment value 2
i need to display total
i tried this code
static int i = 0;
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
i += 2;
Label1.Text = "hello"+i;
}
its working but problem is if user first select 1 in dropdown //i=2 then user select b //i=4 if user again select 1 //i=6. it should not increment if user select any value in particular drop down list. how to do it. any idea....
You're using a static variable so the i value will be kept between postbacks and will be common to all users, this is incorrect.
You need to store it in ViewState, HiddenField, or Session in order to keep the value between postbacks and also keep the value different for each user.
Here's what I would've done using ViewState:
private int Counter
{
get
{
if (ViewState["Counter"] == null)
{
return 0;
}
else
{
return (int)ViewState["Counter"];
}
}
set
{
ViewState["Counter"] = value;
}
}
private bool DropDown1Selected
{
get
{
if (ViewState["DropDown1Selected"] == null)
{
return false;
}
else
{
return (bool)ViewState["DropDown1Selected"];
}
}
set
{
ViewState["DropDown1Selected"] = value;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!this.DropDown1Selected)
{
this.DropDown1Selected = true;
this.Counter += 2;
}
Label1.Text = string.Format("hello{0}", this.Counter);
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
this.Counter += 2;
Label1.Text = string.Format("hello{0}", this.Counter);
}
Few of the answers above are talking about static variable getting reset after post back, this is incorrect, Static variables keep their values for the duration of the application domain. It will survive many browser sessions until you restart the web server Asp.net Static Variable Life time Across Refresh and PostBack
That being said, it is definitely not a good idea to use Static variables and instead go with the approaches suggested using Session or Viewstate.
About your question, I guess you want to increment the value only first time a value is chosen from the drop down list, to achieve this you would want to have a flag to let you know if the value is already selected, something on the below lines:
static bool DrpDown1;
static bool DrpDown2;
static int i = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DrpDown1 = false;
DrpDown2 = false;
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown1)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown1 = true;
}
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
if (!DrpDown2)
{
i += 2;
Label1.Text = "hello" + i;
DrpDown2 = true;
}
}
You need a temporary store like ViewState or Session to keep you values and get it back from
there.
private int GetValue()
{
return Int32.Parse(ViewState["temp"]);
}
private void SetValue(int i)
{
if(ViewState["temp"]==null)
{
ViewState["temp"]=i;
}
else
{
ViewState["temp"]= i+Int32.Parse(ViewState["temp"]);
}
}
and use it in your code as follows
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
SetValue(2);
Label1.Text = string.Format("hello{0}", GetValue());
}

DropDownList SelectedValue doesn't Change

In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protected void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}
Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}
You don't need to use Redirect and QueryString.
Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).
you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..
You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}

Categories

Resources