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());
}
Related
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.
}
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
}
}
I'm trying to get the value of radio button selection to my listbox, but the listbox always gets the same value even though selection was different. Please help, I am a newbie to coding, I couldn't find any answers on the net either..
Here are the codes I've written:
void rdbtnOne_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnOne.Checked == true)
{
rdbtnOne.Text = "Men";
}
else
{
rdbtnOne.Text = "Women";
}
}
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Add(i + rdbtnOne.Text);
i++;
}
Ok, I have found the solution, FINALLY. The reason that my code did not work in the first place was because I tried to give value by equaling rdbtnOne.Text directly. Instead I created another value to equal it. All right here is how it worked for me:
string MenOrWomen;
void rdbtnTwo_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnTwo.Checked.Equals(true))
{
MenOrWomen = "Women";
}
else
{
MenOrWomen = "Men";
}
}
void rdbtnOne_CheckedChanged(object sender, EventArgs e)
{
if (rdbtnOne.Checked.Equals(true))
{
MenOrWomen = "Men";
}
else
{
MenOrWomen = "Women";
}
}
int i = 1;
void btnOne_Click(object sender, EventArgs e)
{
lstOne.Items.Add(i + MenOrWomen);
i++;
}
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);
}
I have a DropDownList, using which I have to store some values from the CheckBoxList in the database.
Before I select another index from the DropDownList, the values in the CheckBoxList has to be stored, prompting the user with an alert "Save before proceeding".
I am able to display the above mention alert message. But the problem is once i change the index it DropDownList, the previous selected index is lost.
Can someone kindly help me getting the previous selected value and select the same dynamically in DropDownList. Because the value is need to store in database.
The code for displaying alert message is:
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
With the use of Global variables.
Using the code below. PreviousIndex will hold the previous, and CurrentIndex will hold current.
int PreviousIndex = -1;
int CurrentIndex = -1;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
PreviousIndex = CurrentIndex;
CurrentIndex = myDropdownList.Position; // Or whatever the get position is.
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
You can get the selected value first time the page load as
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Because When postback occurs the selected valued changed.
{
ViewState["PreviousValue"] = ddl.SelectedValue;
}
}
and in your selected index change event update your previous value by the new value as
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["NewValue"] = ddl.SelectedValue;
// Do your work with PreviousValue and then update it with NewValue so next you can acces your previousValue using ViewState["PreviousValue"]
ViewState["PreviousValue"] = ViewState["NewValue"];
}
or If you want to access selected value on different pages then save it in Session.
you can try with this code - bu using session caching
public string YourOldValue
{
get
{
if(Session["key"] != null)
return (string) Session["key"];
}
set
{
Session["key"] = value;
}
}
//Set value
YourOldValue = yourControl.SelectedValue;
protected void LOC_LIST2_SelectedIndexChanged(object sender, EventArgs e)
{
Session["SavedItem"] = LOC_LIST2.SelectedItem;
if (CheckBoxList2.Items.Count > 0)
{
Label7.Visible = true;
Label7.Text = "*Save List Before Proceeding";
}
}
after you access on value or text
SelectedItem item = Session["SavedItem"] as SelectedItem;
if(item !=null)
{
string something= item.Value;
string otherthing =item.Text;
}
So here's what finally worked for me. A combination of the answers above.
You have to track both previous and current selected index/value in the OnLoad handler of the page/control.
private int PreviousSelectedIndex
{
get { return (Page.ViewSate["prevIdx"] == null) ? -1 : (int)ViewSate["prevIdx"]; }
set { Page.ViewSate["prevIdx"] = value; }
}
private int CurrentSelectedIndex
{
get { return (Page.ViewSate["currIdx"] == null) ? -1 : (int)ViewSate["currIdx"]; }
set { Page.ViewSate["currIdx"] = value; }
}
protected override void OnLoad(EventArgs e)
{
if (!Page.IsPostBack)
{
PreviousDropDownValue = ddlYourDropDownList.SelectedValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
else if (Page.IsPostBack && CurrentDropDownValue != ddlYourDropDownList.SelectedValue)
{
PreviousDropDownValue = CurrentDropDownValue;
CurrentDropDownValue = ddlYourDropDownList.SelectedValue;
}
}
After that you can compare the previous and current values with each other.