I have a boolean variable declared at the top of a class and when a radio button is selected on a page, the variable gets set to true, but when the page is reloaded, the variable gets reset back to false. One way I have handled this was by using the static keyword, but I am not sure if this is the best way to handle this. Here is the class where I tried doing things in the Page_Load event, but it is still resets the variables to false.
public class SendEmail
{
bool AllSelected;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
AllSelected = false;
}
}
protected void rbAll_SelectedIndexChanged(object sender, EventArgs e)
{
if(rbAll.SelectedValue == "All")
AllSelected = true;
}
public Send()
{
if(AllSelected)
{
//Send Email. Never runs because AllSelected is always false;
}
}
}
When the page gets reloaded, a new instance of your page class is created so any values from the last server interaction are lost. Put the value into viewstate if you want it to persist across postbacks:
bool AllSelected
{
get
{
object o = ViewState["AllSelected"];
if(o == null) return false;
return (bool)o;
}
set
{
ViewState["AllSelected"] = value;
}
}
The ViewState collection is written in a hidden element into the form in the client's browser, and posted back and restored the next time they click a button or do any other "postback" type action.
Every time asp.net serves a page, it creates a new instance of the page class. This means that AllSelected will always be auto initialized to false.
My suggestion, unless there is something I don't see here, is to just call Send() from your SelectedIndexChanged method.
You need your variable to be stored. I'd suggest storing it in ViewState or if you want to stay away from ViewState, hide it in a form element on the page.
Also, I'm not seeing where Send is being called.
Your boolean is an instance variable, so it will get the default value (which is false for bools) every time you create a new instance of your class.
Remember, every request to your page uses a brand new instance of your page class. This includes postbacks.
Not to jump down on you or anything...but why not just check if
rbAll.SelectedValue == "All"
in your send function?
No storage...no populating the ViewState or Session with data that isn't needed...
I don't really know if this is going to be handy in asp.net but I create a new bool in property.settings so that it remembers the bool whenever I close or restart the application. But I think this is more for winforms.
Related
I have the following snippet of code that allows me to pull the properties from an object in my list and assign them to variables in other forms. However, I need to be able to pull the data from my variables in the other form and use those to set the properties of the given object.
My class Account is used to populate my list accounts. On my next form AccountMenu I have a class Variables1 that contains accessible variables that are used throughout the rest of my forms to keep track of the checking balance and saving balance. When logging off from the AccountMenu, I want to be able to pass the values from Variables1 to the account that was initially used.
I know how to pass variables from one form to another, but I'm not really sure how to update the form automatically, without a button, on the original form. Thus, the solution that I see is that I have a button on my AccountMenu form that "logs" the user out, via this.close(); Additionally, I guessed that under that button, I need to have some code that assigns the variables as properties to the object. I'm just not sure how I can access the set properties of the object, since it is dynamically called with the code below.
Can someone help me figure out what I need to do? Below is some of the relevant code so that you can see how I have things set up. I am just not sure how to access "matches" from the other form in order to update that specific object properties. Thank you, anyone, who can help!
//variable that will be used to check textbox1.Text
string stringToCheck;
//array of class Account
List<Account> accounts = new List<Account>();
public MainMenu()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//set value to user's input
stringToCheck = textBox1.Text;
//set a var that only returns a value if the .Name already exists
var matches = accounts.FirstOrDefault(p => p.Name == stringToCheck);
//check through each element of the array
if (matches == null)
{
accounts.Add(new Account(stringToCheck));
textBox1.Text = "";
label3.Visible = true;
}
else if (matches != null)
{
//set variables in another form. not sure if these are working
Variables1.selectedAccount = matches.Name;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = matches.CheckBalance;
//same thing?
Variables1.selectedSaveBalance = matches.SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
this.Hide();
acctMenu.Show();
}
}
As per my understanding I think what you required is kind of trigger on your parent form that needs to be called from your child application.
If that is what you required than you can go with defining an event on your AccountMenu form. and register this event from your Accounts form.
Than simply raise this event from your AccountMenu subform.
Deletegates and Events are really works like magic :)
Let me show you some code how to do this.
Code required in AccountMenu window:
public delegate void PassDataToAccounts(string result);
public event PassDataToAccounts OnPassDataToAccount;
protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{
if (OnPassDataToAccount != null)
OnPassDataToAccount("result");
base.OnClosing(e);
}
Code required in Accounts window button1_Click event where the AccountMenu will open:
//set variables in another form. not sure if these are working
Variables1.selectedAccount = matches.Name;
//is this calling the CheckBalance of the instance?
Variables1.selectedCheckBalance = matches.CheckBalance;
//same thing?
Variables1.selectedSaveBalance = matches.SaveBalance;
//switch to form
AccountMenu acctMenu = new AccountMenu();
acctMenu..OnPassDataToAccount += childwindow_OnPassDataToAccount;
this.Hide();
acctMenu.Show();
}
void childwindow_OnPassDataToAccount(string result)
{
if (result == "result")
{
// Processing required on your parent window can be caried out here
//Variables1 can be processed directly here.
}
}
I am perplexed, and maybe I am just familiar with the properties of pageLoad, IsPostBack, or IsCallback. I created a Boolean variable called "first" and set it to True.
First time through PageLoad, there is a line of code if first = False, if so, write = true.
Then I have a Run_write routine attached to a button, when it runs, if the user response Yes, to the initial question, I make another group of radio buttons visible and set first to false. (i ran this in debug, and I know it hits this line of code) ... so the write to sql is ignored because write == false and the window reappears with the new set of Buttons... Great!
Furthermore, I go through the PageLoad routine again, and it hits the line if (!first), set write to TRUE. my issue is first has been re-set to true? What am I missing?
Note, I was able to work around this by utilizing whether the new set of buttons is checked, but I may not want to go this route, and I do want to understand what is going on.
code is below.
namespace MEAU.Web.Components.SupportCenter
{
public partial class feedback : System.Web.UI.Page
{
String login;
String myurl;
String response;
String s_call;
String p_ship;
String wrnty;
Boolean write;
Boolean first = true;
protected void Page_Load(object sender, EventArgs e)
{
login = Sitecore.Security.Accounts.User.Current.Profile.Email;
myurl = Request.QueryString["value"];
s_call = "No";
p_ship = "No";
wrnty = "No";
// Hide the question Buttons
scall.Visible = false;
parts.Visible = false;
wrnt.Visible = false;
lit.Visible = false;
write = false;
if (!first)
write = true;
}
protected void Run_Write(object sender, EventArgs e)
{
// Get Reponse
if (yes.Checked)
{
response = "Yes";
// Display the quesiton buttons, and Hide the NO button
scall.Visible = true;
parts.Visible = true;
wrnt.Visible = true;
lit.Visible = true;
no.Visible = false;
first = false;
// Did this Prevent a Service call?
if (scall.Checked)
{
s_call = "Yes";
write = true;
}
// Did this Prevent a parts shipment?
if (parts.Checked)
{
p_ship = "Yes";
write = true;
}
// Is this under warranty?
if (wrnt.Checked)
{
wrnty = "Yes";
write = true;
}
// write = true;
}
if (no.Checked)
{
response = "No";
write = true;
}
if (write == true)
{
SqlConnection conn = new SqlConnection(Sitecore.Configuration.Settings.GetConnectionString("feedback"));
SqlCommand cmd = new SqlCommand("Insert_fb", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#login", login);
cmd.Parameters.AddWithValue("#url", myurl);
cmd.Parameters.AddWithValue("#response", response);
cmd.Parameters.AddWithValue("#dateTime", DateTime.Now);
cmd.Parameters.AddWithValue("#serviceCall", s_call);
cmd.Parameters.AddWithValue("#partsShipment", p_ship);
cmd.Parameters.AddWithValue("#warranty", wrnty);
try
{
conn.Open();
cmd.ExecuteNonQuery();
Response.Write("<script type='text/javascript'>parent.$.fancybox.close();</script>");
Response.Write("<script type='text/javascript'>return false;</script>");
}
catch (Exception ex)
{
throw new Exception("Error on file update" + ex.Message);
}
finally
{
conn.Close();
}
}
}
}
}
Every HTTP request to your site creates a new instance of your page class.
Instance state is not preserved.
Instead, you need to store the state in session or ViewState, depending on what you want to apply to.
Page_Load will be called every time your server is requested for the page. This includes post-backs.
You can check IsPostBack to see if the current Page_Load execution is for the first display of the page, or a subsequent post-back.
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
// Do first-time things
}
else
{
// Do non-first-time things
}
}
Note that the particular instance of your page object will not persist from access to access. So there may be some information that you need to initialize every time the page is called.
Every time you visit the page, you're creating a new instance of the class.
To distinguish a page load from a user clicking a button vs. a user arriving on the page for the first time, you want to check the IsPostBack property.
So rewrite your if along the lines of
// Code that always executes
if (IsPostBack)
{
// Code that only executes on initial page load
}
else
{
// Code that only executes when a postback event occurs
// e.g. A user clicks on a button.
}
There are some ways by which you can maintain the state or value of the controls, so I have been maintaining the Viewstate of the controls in the not is postback, as check of
(!IspostBack) // means when page loads first time
and whatever written in the else means when postback occurs in which you can maintain the viewstate of the objects.
Also we can use the session, if Viewstate is not used.
Rykiel,
the basic concept of the web is (state-less), and that why you have to handling, but anyway you can read about page life cycle I recommend you read it http://www.codeproject.com/Articles/20659/The-ASP-NET-Page-Lifecycle-A-Basic-Approach
you can use
if(!isPostBack)
{
first=true;
this portion of code only run when the page is requested first time
}else
{
first = false;
}
if you change the value of control in the page or click a button isPostBack will be true. but if you refresh the page or hit F5 you page will be requested again and isPostBack will be false;.
also you can use cookies or session variable (I also recommend do not load too much the Session Variable). try to read the prior link and you will be more clear where put your code to get the best performance.
J.S.
The answers on here are good, but technical. I will try to explain a little of what is happening.
When a browser requests your page, and on the server, a new instance of your class is created.
ASP.NET then runs the rest of the page, starting with your page_load. This will call all your other functions and then render the HTML as a response to your request and send it back to the browser. I like to explain this as a disconnected environment. Once the response is sent, everything is disposed of in a sense. Your variables, previous work, etc... are all gone. The Server as far as it is concerned, never expects to get anything from the browser again... its done its job. It took your request for a page, created a result and posted it back to the browser. Done.
So, think of your code as a new request each time it is called.
You can use the IsPostback as stated by ThatBlairGuy, because that will return true if you are responding to a postback from the browser, meaning that it has already served up this page to the browser on the previous postback.
I have a Button_click event. While refreshing the page the previous Postback event is triggering again. How do I identify the page refresh event to prevent the Postback action?
I tried the below code to solve it. Actually, I am adding a visual webpart in a SharePoint page. Adding webpart is a post back event so !postback is always false each time I'm adding the webpart to page, and I'm getting an error at the else loop because the object reference is null.
if (!IsPostBack){
ViewState["postids"] = System.Guid.NewGuid().ToString();
Cache["postid"] = ViewState["postids"].ToString();
}
else{
if (ViewState["postids"].ToString() != Cache["postid"].ToString()){
IsPageRefresh = true;
}
Cache["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Cache["postid"].ToString();
}
How do I solve this problem?
using the viewstate worked a lot better for me as detailed here. Basically:
bool IsPageRefresh = false;
//this section of code checks if the page postback is due to genuine submit by user or by pressing "refresh"
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
IsPageRefresh = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
This article could be of help to you
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
you are adding a Guid to your view state to uniquely identify each page. This mechanism works fine when you are in the Page class itself. If you need to identify requests before you reach the page handler, you need to use a different mechanism (since view state is not yet restored).
The Page.LoadComplete event is a reasonable place to check if a Guid is associated with the page, and if not, create one.
check this
http://shawpnendu.blogspot.in/2009/12/how-to-detect-page-refresh-using-aspnet.html
This worked fine for me..
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
Simple Solution
Thought I'd post this simple 3 line solution in case it helps someone. On post the session and viewstate IsPageRefresh values will be equal, but they become out of sync on a page refresh. And that triggers a redirect which resets the page. You'll need to modify the redirect slightly if you want to keep query string parameters.
protected void Page_Load(object sender, EventArgs e)
{
var id = "IsPageRefresh";
if (IsPostBack && (Guid)ViewState[id] != (Guid)Session[id]) Response.Redirect(HttpContext.Current.Request.Url.AbsolutePath);
Session[id] = ViewState[id] = Guid.NewGuid();
// do something
}
If you want to detect a refresh on an HTTP GET rather than only POSTs, here's a hacky work-around that, in modern browsers, mostly works.
Javascript:
window.onload = function () {
// regex for finding "loaded" query string parameter
var qsRegex = /^(\?|.+&)loaded=\d/ig;
if (!qsRegex.test(location.search)) {
var loc = window.location.href + (window.location.search.length ? '&' : '?') + 'loaded=1';
window.history.replaceState(null, document.title, loc);
}
};
C#:
public bool IsPageRefresh
{
get
{
return !string.IsNullOrEmpty(Request.QueryString["loaded"]);
}
}
When the page loads, it will change add a QueryString parameter of loaded=1 without reloading the page (again, this--window.history.replaceState--only works in post-archaic browsers). Then, when the user refreshes the page, the server can check for the presence of the loaded parameter of the query string.
Caveat: mostly works
The case where this doesn't work is when the user clicks the Address Bar and presses enter. That is, the server will produce a false-positive, detecting a refresh, when odds are, the user actually meant to reload the page fresh.
Depending on your purposes, maybe this is desirable, but as a user, it would drive me crazy if I expected it to reset the page.
I haven't put too much thought into it, but it might be possible to write some magic in order to distinguish a refresh from a reset via the address bar using any/all of:
SessionState (assuming SessionState is enabled) and the value of the loaded QueryString parameter
the window.onbeforeunload event listener
keyboard events (detecting F5 and Ctrl + R to quickly change the URL back to removing the loaded QueryString parameter--though this would have a false-negative for clicking the browser's refresh button)
cookies
If someone does come up with a solution, I'd love to hear it.
Another way to check page refresh. I have written custom code without java script or any client side.
Not sure, it's the best way but I feel good work around.
protected void Page_Load(object sender, EventArgs e)
{
if ((Boolean)Session["CheckRefresh"] is true)
{
Session["CheckRefresh"] = null;
Response.Write("Page was refreshed");
}
else
{ }
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CheckRefresh"] = Session["CheckRefresh"] is null ? false : true;
}
I have a simple question in asp.net.
I want to know if it is possible to get data from controls in my user control directly . I want to do it without using Session variable,Viewstate ...
EDIT: I now use the method of declaring public variables in the UC.
Here is a part of Page_load from my parent page:
this.plan_action = (UCPlan)Page.LoadControl("~/Association/UCPlan.ascx");
PlaceHolder1.Controls.Add(this.plan_action);
if (this.plan_action.Validate == true)
{
CheckBox1.Checked = true;
//String référence = Session["liste_action"].ToString();
for (int i = 0; i < this.plan_action.List1.Count; i++)
{
Label8.Text += this.plan_action.List1[i].Référence + "/";
//Label8.Text += "/";
}
}
but my variable validate stay to false.
Here is the code where I change the value of the validate variable with it declaration:
private bool validate;
public bool Validate
{
get { return validate; }
set { validate = value; }
}
protected void Button2_Click(object sender, EventArgs e)
{
//myCommand.Connection = myConnection;
//Session["liste_action"] = this.List;
this.Validate = true;
//Response.Redirect("../Risques_folder/AjouterRisque.aspx");
}
Thank you for your help,
Quentin
UPDATE due to new information
You need to learn about the sequence of events in ASP.NET.
The Load of the page happens a long time before the Click handler of Button2 in your UserControl... so the Validate property is always going to be set to false.
You have two obvious options (as I see it)...
Keep the creation of the UserControl in your Page_Load (or preferably, move it to your Page_Init, as this is normally the most appropriate place for it). Then place your check for the Validate property in a Page_PreRender.
Or, create an Event in your UserControl, Raise that event on the click of Button2, and handle the event in the Page.
ANOTHER UPDATE
For the 2nd of the two options above, in your UserControl class have the following...
public delegate void ButtonClickedDelegate(object sender, EventArgs e);
public event ButtonClickedDelegate ButtonClicked;
In the Button2_Click method of the UserControl (after setting the this.Validate = true;) call...
ButtonClickedDelegate(sender, e);
In the Page_Init of the Page, put something like...
ctrl1.ButtonClicked += new UCPlan.ButtonClickedDelegate(ctrl1_ButtonClicked);
And then have a new method called something like
void ctrl1_ButtonClicked(object sender, EventArgs e)
{
if (ctrl1.Validate)
{
...
}
}
Remember, as you control the delegate you can pass whatever information you want, including an entire class. So instead of calling the Validate property, create a new instance of the class you want, and pass that as a delegate parameter.
You can find more information on delegates and events on MSDN.
ORIGINAL ANSWER
Unless I've missed something, this is a very simple ASP.NET concept...
You can create properties and/or methods.
For example, as a property...
public string MyProperty
{
get { return "My Property Value"; }
}
Or as a method
public string MyMethod()
{
return "My Method Value";
}
If you're talking about passing the values between the UserControl and the ASP.NET Page that contains it, then in your Page, you can simply call the property or method. If your control was called (for example) myCtrl, then you can something like...
string prop = myCtrl.MyProperty;
string meth = myCtrl.MyMethod();
(On the back of the great comment from AHMED EL-HAROUNY)
If you're talking about passing the values to the client side page, then you can use the same properties / methods directly in the HTML markup. However, in this case, the properties / method can be declared as protected rather than public
For instance, to display the value...
<%=MyProperty%>
Or
<%=MyMethod()%>
Or if you're going to use the value in javascript, something like...
var myProp = "<%=MyProperty%>";
Yes That is possible, But exposing the controls in the UserControl as Public.
Here I'm facing problem,I'm adding form dynamically into tab page.
I have to get a static variable from that form.
i used code,but i can't get exact value which i need.
private void timer2_Tick(object sender, EventArgs e)
{
foreach (TabPage page in tabControl1.TabPages)
{
Control control = page.Controls[0];
if(!hyber.Form1.receiverflag)//bug line
{
tabControl1.TabPages.Remove(page);
}
}
}
In the above pic watch window
page.controls[0]
->[hyber.form1]
-->receiverflag
how to get that variable value.
Thanks in advance.
you are nor clear about bug line or in saying can't get the exact value you need.
if the variable is a public static bool it belongs to the class and not to the instance, being static, so when you write:
hyber.Form1.receiverflag
you are taking the variable's value regardless of the specific instance of Form1 you are dealing with, does not matter at all if you have created one instance and added to the TabPage, that variable always exists even if you do not create any instance.
if you are getting wrong/unexpected results could be, eventually, that another thread or another method has changed the value of that static field and this reflects everywhere in your application.
Edit: if it was not static, you could probably get what you are asking in this way:
var yourForm1 = (page.Controls[0] as hyber.Form1);
if( yourForm1 != null && !yourForm1.receiverflag)
{
....