In the code below, how do I declare totalSquareFeet and other variables global so that when I parse data from asp.net textboxes it becomes accessible to other methods specifically performAnalysisButton button method?
Note that the code below is not complete. I have deleted most of the code to keep my question as simple as possible. To give you a background following are the purposes of 2 buttons:
okButton_Click: Take the data from textboxes (created in asp.net webform) and perform some calculations and display results in labels.
performAnalysisButton_Click: Take the data from aforementioned textboxes and perform some calculations and display results in another textbox.
In short, all the local variables that I have declared under the okButton_Click method, I would like to use them under performAnalysisButton_Click method. I was wondering if there is a way I can avoid parsing the textbox data again?
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Create objects for fiscal year end dates (e.g. 12/31/17)
FiscalYearEnds fiscalYearEnds = new FiscalYearEnds();
firstFiscalYearEndLabel.Text = String.Format("{0:MM/dd/yyyy}", fiscalYearEnds.firstFiscalYearEndDate());
secondFiscalYearEndLabel.Text = String.Format("{0:MM/dd/yyyy}", fiscalYearEnds.secondFiscalYearEndDate());
}
protected void okButton_Click(object sender, EventArgs e)
{
// Parse values
int totalSquareFeet = int.Parse(totalSqFtTextBox.Text);
int totalOccupiedSquareFeet = int.Parse(occupiedSqFtTextBox.Text);
decimal grossRentsFirstYear = decimal.Parse(grossRentsFirstYearTextBox.Text);
decimal grossRentsSecondYear = decimal.Parse(grossRentsSecondYearTextBox.Text);
int loanAmount = int.Parse(loanAmountTextBox.Text);
double interestRate = double.Parse(interestRateTextBox.Text);
int loanTerm = int.Parse(yearlyLoanTermTextBox.Text);
}
protected void performAnalysisButton_Click(object sender, EventArgs e)
{
Analysis analysis = new Analysis();
analysis.GrossRentFirstYear = decimal.Parse(grossRentsFirstYearTextBox.Text);
analysis.GrossRentSecondYear = decimal.Parse(grossRentsSecondYearTextBox.Text);
analysisAndComments.Text = String.Format("{0}", analysis.PerformAnalysis());
}
}
After roundtrip the page returns to the client and there will be no information saved on the server unles you save it somewhere. Meaning you can hold the extra information on the page inside a hiddenfield or you can store it inside a Session or ViewState
Session This will be saved on the server(Also available if you go to other page)
Session["totalSquareFeet"] = totalSquareFeet;
Then you can read it back in performAnalysisButton_Click
int totalSquareFeet = (int)Session["totalSquareFeet"];
if you wanna clean the Session var after leaving page you can do
Session["totalSquareFeet"] = null;
ViewState This will be saved on the page(Credits to Alexandru Popa)
ViewState["totalSquareFeet"] = totalSquareFeet;
Read
int totalSquareFeet = (int)ViewState["totalSquareFeet"];
Hiddenfield This will be saved on the page
store it in a <asp:HiddenField ID="HiddentotalSquareFeet" runat="server" />
HiddentotalSquareFeet.Value = totalSquareFeet.ToString();
And read it back
if(int.TryParse(HiddentotalSquareFeet.Value, out int totalSquareFeet)){
}
If I understood your question right...
To declare a variable as global, all you need to do is to declare it outside of the function and inside of the class that you are working in:
public partial class Default : System.Web.UI.Page
{
int totalSquareFeet = 0;
protected void Page_Load(object sender, EventsArg e)
{ // And the rest of the code should be the same...
}
// Same code as you had...
}
So, it's al about removing the declaration from within the function to the outside.
I solved the problem by declaring properties at the class level and that became my global variables which I can access in button methods. Now I don't need to parse textbox values again in the button methods. See example below:
public int totalSquareFeet
{
get { return int.Parse(totalSqFtTextBox.Text); }
set { int.Parse(totalSqFtTextBox.Text); }
}
Related
I'm relatively new to C# and VS, and currently having a play with ASP.NET, but I seem to be getting very muddled on where I should place my objects that I need to use within my webforms. As a very basic example, how could I add a counter button? With the code below, when you click the button nothing changes and the textbox just shows The count is 2'. I think this is because the page is reloading each time and therefore the Counter object gets 're' instantiated. So how do I avoid that?
Default.aspx
...
<asp:Button ID="bttnCounter" runat="server" Text="Click Me" OnClick="ButtonClick"/>
...
Default.aspx.cs
public partial class _Default : Page
{
Counter counter = new Counter();
protected void Page_Load(object sender, EventArgs e)
{
bttnCounter.Click += new EventHandler(this.ButtonClick);
}
public void ButtonClick(Object sender, EventArgs e)
{
counter.CountUp();
output.Text = "The count is " + counter.CurrentCount;
}
}
Counter.cs
public class Counter
{
public int CurrentCount { get; private set; }
public Counter()
{
CurrentCount = 0;
}
public void CountUp()
{
CurrentCount++;
}
}
I may have just completely mis understood this, but when I was using WinForms, I would include the object within the form code.
You should save it in the pages ViewState, since that is the only persistent user-based storage that isn't session bound (you can open the same page multiple times).
this.ViewState["someVar"] = yourObject;
Retrieve it later:
YourClass yourObject = (YourClass)this.ViewState["someVar"];
You are correct, the page is loading each time and thus resets your counter to zero each time you click the button.
there are a number of approaches to solve this, the simplest is perhaps to use the Session["counter"] object to store the counter and reload it on page load.
However, as you are new I would suggest you abandon this style of asp.net and instead learn the new MVC version
this has a different approach which avoids many of the page lifecycle problems of asp.net (webforms) although you will still need to store the counter either on the server, or in the page response to the user so it can be sent back in the query string, cookie or whatever
I have public variables:
public static List<CompanyModel1> companies1 = new List<CompanyModel1>();
public List<URL> urls = new List<URL>();
I add more values to this variable during a function call
public void DataBind_Results()
{
..companies1.AddRange(listToAdd.OrderByDescending(c => c.compnMastery1));
}
urls.Add(new URL
{
Link = listToAdd.First().compnId1.ToString(),
Title = arrProcess[ar]
});
But my code always run twice (I see that when I use debug), I think the reason is it always have page reload.
Then my variable will be duplicate its values, and when I the data display, I see it is duplicated. How to avoid it ?
I'm going to assume you're using asp.net or something. Wrap the "add" function in an
if(!Page.IsPostBack) {
//Your add code
}
Ideally, find out why your page is loading twice then fix that.
Then add code to check whether the lists are populated at the start of each data bind before they are re-populated.
You want the variable to populate OnLoad so do something like this:
Declare your variables:
public static List<CompanyModel1> companies1;
public List<URL> urls;
The populate them when the page loads. But not if you're doing a postback.
protected override void OnLoad(EventArgs e)
{
if(!IsPostBack)
{
companies1 = new List<CompanyModel1>();
urls = new List<URL>();
}
}
Your code is running twice that means, once when you call that function and again when the page is posted back.
Put your code in
if(!IsPostBack)
{
here.....
}
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.
i am developing a web for my final project,and im new to ASP.NET and this forum.
thx to all who help me.
the question is...
example i have 2 pages.
page1.aspx.cs (this page for receive variable from mikrokontroler via network module)
example mikrokontroler send a variable "status" = 1
protected void Page_Load(object sender, EventArgs e)
{
NameValueCollection POST = Request.Form;
int STATUS;
int responcode;
try
{
A = int.Parse(POST["status"]);
}
catch (Exception)
{
status = 0;
}
if (A == 1)
{
responcode = 200;
//when A = 1, i want to store A value to (buffer on something <-- this what i want to ask)).
so i can call the value anytime in page2.
}
else
{
responcode = 400;
}
Response.StatusCode = responcode;
}
}
}
page2.aspx
(in page 2 there is button and textbox)
protected void Button3_Click(object sender, EventArgs e)
{
/*when this button click,
i want to show A value from page1
*/
}
You have a lot of options to store the variable value:
session state: Session["status"]= A
application state: Application["status"] = A
asp net cache: using Cache.Add()
database: here i would store also the timestamps, to trace the historic status of the controller.
local XML file.
It all depends on the scope of the stored data: session data is local to the current user/session and will expire after a predefined timeout(def: 20mins), application will be global to all your users/sessions and will expire when you will restart the application (by iis, iisreset, recompiling...), cache is global and will expire based on the parameters of invocation, the database and xml are global and will maintain state.
In your case i would use database or application store, because the microcontroller and user live in different sessions and the app cache is not a suitable messaging mechanism while Xml introduces some problems on his own (eg: filesystem permissions, data replication...).
write:
Application["status"] = A;
read:
int A = 0;
bool result = int.TryParse(Application["status"],out A);
BTW: to parse the integer you can skip the try/catch part doing this:
int A = 0;
bool result = int.TryParse(POST["status"],out A);
in this case if unable to parse A will be equal to 0;
You can use Session
NameValueCollection POST = Request.Form;
int STATUS;
int responcode;
try
{
A = int.Parse(POST["status"]);
}
catch (Exception)
{
status = 0;
}
if (A == 1)
{
responcode = 200;
//when A = 1, i want to store A value to (buffer on something <-- this what i want to ask)).
Session["Avalie"] = A;
so i can call the value anytime in page2.
}
else
{
responcode = 400;
}
Response.StatusCode = responcode;
}
}
and then on page 2
protected void Button3_Click(object sender, EventArgs e)
{
/*when this button click,
i want to show A value from page1
*/
if(!String.IsNullOrEmpty( Session["Avalie"] ))
int Aval = int.Parse(Session["Avalie"]);
}
Use crosspagepostback to pass values from one page to another (introduced in asp.net 2.0)
One option is to assign the value to a static variable in the first page.
Refer to Static Classes and Static Class Members (C# Programming Guide)
Another option is to use state variables as session state variables or application variables.
Refer to ASP.NET Session State Overview and ASP.NET Application State Overview
I have something to do under a button click (add values to listbox) only if a particular string changes from its previous value. How do I manage this? Below is a sample of my code:
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
I can at times have same value for string x from previous value when clicking button6. In such cases I don't want listBox1 to add the item (string x). How to add to listbox only when value of string changes? There's no way to predetermine string x. It gets value when program is running.
Note: adding values to listBox1 every single time and later deleting the duplicates wont work in my program.
Have you considered keeping a copy of the old string value around in a private field, and simply comparing the new value to the old value to see if they match?
For example:
// holds a copy of the previous value for comparison purposes
private string oldString = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
// Get the new string value
string newString = //some varying value I get from other parts of my program
// Compare the old string to the new one
if (oldString != newString)
{
// The string values are different, so update the ListBox
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
}
// Save the new value back into the temporary variable
oldString = newString;
}
Edit: As the other answers suggest, there are certainly other, more complicated solutions, like encapsulating all access to the string value in a property, or wrapping the string in a custom class. Some of these alternatives have the potential to be "cleaner", more object-oriented approaches. But they're all more complicated than simply saving the previous value in a field. It's up to you to decide whether your specific use case merits the complicated solution, or a simpler one. Think about long-term maintainability, not what's easier for you to implement right now.
string last = string.Empty;
private void button6_Click(object sender, EventArgs e)
{
string x = //some varying value I get from other parts of my program
if(x!=last)
{
listBox1.Items.Clear();
listBox1.Items.Add(x + /*other things*/);
last = x;
}
}
If this string is super important and gets passed around alot, maybe you should wrap it in a class. The class can hold the string value as a property, but also keep track of when it has changed.
public class StringValue
{
private bool _changed;
public string StrValue{get; set{ _changed = true;}
public bool Changed{get;set;}
}
this is rudimentery of course
I'm not sure I understand completely, but it sounds like you should be using a property to set String x;
string _x = string.Empty;
public string X
{
set
{
if(value != this._x)
{
DoFancyListBoxWork();
this._x = value;
}
}
get
{
return this._x;
}
}
If this is web application, store your last value into session variable. If this is windows application, store it at a class level variable or in singleton class and use this last value for comparison with new value.
On the page load add the current value to viewstate and at the button click check the current value is equal to the value in the view state. If both are equal we can say that the value is not changed.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["CurrentValue"] = Your Value;
}
}
protected void btnSubmit_click(object sender, EventArgs e)
{
if (NewValue== ViewState["CurrentValue"].ToString())
{
lblmsg.Text = "value is not changed..";
return;
}
else
lblmsg.Text = "value is changed..";
}
You can check the detailed article in this link.
Check Control Value is changed or not
First, I'd like to ask you to check most of the other answers. They are more complete, in that they treat more global issues of tracking the changes of a variable.
Now, I'm assuming, from reading the snippet of code you provided, that you need to track if a string was changed by the user. So, in other words, you probably have a TextBox or other kind of control through which the user can change that value. This is where you should focus your attention: just consume the TextChanged event.
If, however, I'm mistaken and your string comes from any other kind of external source, either use the wrapper class suggested by #Ryan Bennett or, if you are using .Net 4, use a dynamic container, which raises a PropertyChanged event whenever any property is changed.