Im trying to set a value in a method as shown below but when i run btnSaveValue there is no value to retrieve. Ive even tried creating a private int val in the defaul class and assigning the value to that but still a blank value comes through - can anyone help me out?
thanks
public partial class _Default : System.Web.UI.Page
{
valueAllocation valAlloc = new valueAllocation();
public void declaringValue()
{
valAlloc.setValue(5);
int testAlloc = valAlloc.getValue();
lblResult.Text="Value set here is:"+testAlloc; //THIS WORKS!!!
}
protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
lblResult.Text = "Value now is:" + valAlloc.getValue(); //DOESNT WORK??????!!!!!
}
}
public class valueAllocation
{
private int val;
public void setValue(int value)
{
val = value;
}
public string getValue()
{
return val;
}
}
This is because you need to save the value in each post using for example the ViewState.
This is a basic problem related with the ASP.Net page life-cycle.
Basically, every time you request your page, a new instance of the page is created on every post, and destroyed when the response returns to the client
If you want to keep the state across post backs, you need to manually save each value in the ViewState
storing the whole type in the ViewState
I think this is your best bet
Custom Type
[Serializable]
public class valueAllocation
{
public int MyValue { get; set; }
}
Code behind
protected valueAllocation MyObject
{
get
{
if(this.ViewState["c"] != null)
return (valueAllocation)this.ViewState["c"];
return null;
}
set
{
this.ViewState["c"] = value;
}
public valueAllocation declaringValue()
{
if (this.MyObject == null)
this.MyObject = new valueAllocation { MyValue = 5 };
lblResult.Text="Value set here is:"+ this.MyObject.MyValue.ToString();
return this.MyObject;
}
protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
declaringValue()
lblResult.Text = "Value now is:" + declaringValue().MyValue.ToString();
}
The problem is you never called decalringValue(), do this
public valueAllocation declaringValue()
{
valAlloc.setValue(5);
int testAlloc = valAlloc.getValue();
lblResult.Text="Value set here is:"+testAlloc; //THIS WORKS!!!
return valAlloc;
}
protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
declaringValue()
lblResult.Text = "Value now is:" + declaringValue().getValue(); //DOESNT WORK??????!!!!!
}
It is because this is web application not a desktop.You have to manage the state of page.Because on web each request is new to server.
for your scenario you have to use "viewstate" technique for maintain the state of your page.
or you have to make your variable static if you want that value is not lose.
for further details googled "State management in asp.net"
Looks like values were not set using valAlloc.setValue(SomeNumber); before calling the below method
Or I would say that valAlloc.val is having a default value of zero
protected void btnSaveValue_Click(object sender, ImageClickEventArgs e)
{
lblResult.Text = "Value now is:" + valAlloc.getValue(); //DOESNT WORK??????!!!!!
}
so you lblResult.Text is getting a zero from valAlloc.getValue()
Looks like you are looking for a static object and static linkage defined. If a global static object works for you in this case, please vote my reply up.
Related
I have found many answered questions on here explaining how to do this when the objects are created as part of the data source but my list box is just displaying "SharePointXMLBuilder.Farm" (Namespace.class) and not the selected DisplayName?
I dont know what I am doing wrong can anyone help please.
I have a list box with a data source as a databinding control and I am adding my created objects(Farm) to the databinding(farmListBindingSource) which all works fine, I just cant get the list to show the property I want it to.
Form: (loads another form takes input and returns to create object from Farm class)
private void CreateNewFarm_Click(object sender, EventArgs e)
{
FarmInput input = new FarmInput();
input.ShowDialog();
Farm nFarm = new Farm();
nFarm.location = input.inputLocation.ToString();
nFarm.identifier = input.inputType.ToString();
nFarm.environment = input.inputEnvironment.ToString();
this.farmListBindingSource.Add(nFarm);
this.testReturnTextBox.Text = nFarm.friendlyName;
}
private void MainForm_Load(object sender, EventArgs e)
{
this.FarmListBox.DisplayMember = "friendlyName";
this.testReturnTextBox.Text = "Form Loaded....";
}
Class:
namespace SharePointXMLBuilder
{
class Farm
{
private string farmLocation;
private string farmIdentifier;
private string farmEnvironment;
private string farmFriendlyName;
//private List<Server> farmServers;
//properties
public string friendlyName
{
get { return farmFriendlyName; }
set { farmFriendlyName = value; }
}
public string location
{
get { return farmLocation;}
set { farmLocation = value; this.buildFriendlyName(); }
}
public string identifier
{
get { return farmIdentifier; }
set { farmIdentifier = value; this.buildFriendlyName(); }
}
public string environment
{
get { return farmEnvironment; }
set { farmEnvironment = value; this.buildFriendlyName(); }
}
//constructor
public Farm()
{
}
//methods
public void AddServer(string s)
{
Server nServer = new Server(s);
// farmServers.Add(nServer);
}
public void buildFriendlyName()
{
this.friendlyName = this.location + " " + this.identifier + " " + this.environment;
}
}
}
Maybe you are not calling this function: buildFriendlyName() for each object in the list prior to binding?
In your buildfriendlyname() method set your private string farmFriendlyName insted of setting the property value friendlyname
Ok, so I tried to manually add DisplayMember in the designer and it wouldn't hold the value, as soon as I removed the DataSource it allowed DisplayMember to be populated so I changed the CreateNewFarm_Click to add the object to farmListBox.Items and when I re-ran the code it was fine.
It appears that you cannot use DisplayMember if you are pulling the objects from a DataSource.
I'm trying to get a new form (FormAlbum) to open when I click buttonOpenAlbum and have an item selected in the AlbumListBox.
If I just have this in buttonOpenAlbum_Click:
private void buttonOpenAlbum_Click(object sender, EventArgs e)
{
FormAlbum MusicForm = new FormAlbum(this);
MusicForm.ShowDialog();
}
The new from opens without error. However, as soon as I mention "AlbumListBox.SelectedItem" (as in the code belowin Form FormMain), I get a "StackOverflowException was unhandled" at:
public ListBox AlbumListBox
{
get
{ // <-This bracket here is where the error highlights
I don't understand why I'm getting this error, only that it must have something to do with AlbumListBox. What am I doing wrong? Any help is appreciated, thank you.
Form FormMain:
public FormMain()
{
InitializeComponent();
}
private void buttonAddAlbum_Click(object sender, EventArgs e)
{
FormAlbumAC addAlbumForm = new FormAlbumAC(this);
addAlbumForm.ShowDialog();
}
private void buttonOpenAlbum_Click(object sender, EventArgs e)
{
if (AlbumListBox.SelectedItem != null)
{
MessageBox.Show(AlbumListBox.SelectedItem.ToString());
FormAlbum MusicForm = new FormAlbum(this);
MusicForm.ShowDialog();
}
else
{
MessageBox.Show("You need to select an album from the list to open.");
}
}
public static class PublicVars
{
public static List<Album> AlbumList { get; set; }
static PublicVars()
{
AlbumList = new List<Album>(MAX_ALBUMS);
}
}
public ListBox AlbumListBox
{
get
{
return AlbumListBox;
}
}
Look at your property implementation:
public ListBox AlbumListBox
{
get
{
return AlbumListBox;
}
}
It's just calling itself, recursively. It may be easier to see that if we convert it to a method:
public ListBox GetAlbumListBox()
{
return GetAlbumListBox();
}
That's why you've got an overflow. It's not clear what you meant it to do... where did you expect the value to come from? You probably need a variable to back the property. What did you expect to set the value returned?
I'd also strongly discourage the design of the PublicVars class. Aside from the naming, you're basically using global variables - not a good idea. Work out which classes need access to the data, and how to get that data to them appropriately.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Button click event doesn't work properly
I try to increment an int for each click on a default page. Int=0. It only goes up to 1. What should I do to increment the number for each click?
public partial class _Default : System.Web.UI.Page
{
private int speed = 0;
public int Speed
{
get { return speed; } // Getter
set { speed = value; } // Setter
}
public void accelerate()
{
//speed++;
this.Speed = this.Speed + 1;
}
public void decelerate()
{
// speed--;
this.Speed = this.Speed - 1;
}
public int showspeed()
{
return this.Speed;
}
//car bmw = new car();
public void Page_Load(object sender, EventArgs e)
{
//datatype objectname = new
dashboard.Text = Convert.ToString(this.showspeed());
}
public void acc_Click(object sender, EventArgs e)
{
this.accelerate();
dashboard.Text = Convert.ToString(this.showspeed());
}
public void dec_Click(object sender, EventArgs e)
{
this.decelerate();
this.showspeed();
}
}
You could use the ViewState to maintain the value across postbacks:
private int Speed
{
get
{
if (ViewState["Speed"] == null)
ViewState["Speed"] = 0;
return (int)ViewState["Speed"];
}
set { ViewState["Speed"] = value; }
}
You need to store the result in a way that will persist over postback. I suggest using ViewState, for example:
public int Speed
{
get {
if(ViewState["Speed"] == null) {
ViewState["Speed"] = 1;
}
return Convert.ToInt32(ViewState["Speed"]);
}
set {
ViewState["Speed"] = value;
}
}
Because everytime when you click on the button, it is initializing the value of speed to 0.
HTTP is stateless. That means it wil not retain the values of variable across your postback like you do in Windows Forms programming. So you need to keep the value across your postbacks.
You can use a hidden element in your page to store the value and access the value every time you want to do a function on that:
<asp:HiddenField ID="hdnFileId" runat="server" Value="" />
and in your page load, you can read the value and load it to your variable.
public void Page_Load(object sender, EventArgs e)
{
this.speed = ConvertTo.Int32(hdnFileId.Value);
}
From Adrianftode's comment, the data for the controls like TextBox, Checkbox, Radio button controls values will be posted to the server on the postback because they are rendered as standard HTML form controls in the browser. See Chapter 4. Working with ASP.NET Server Controls.
In my ASP.NET page, I have a generic class that is defined as below:
public partial class log_states : BasePage
{
protected class StatesUsed
{
public int StateCode { get; set; }
public string StateName { get; set; }
}
private List<StatesUsed> _statesUsed;
}
In the Page_Load() event, I initialize _statesUsed like below, and bind it to a grid:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
_statesUsed = new List<StatesUsed>();
BindMyGrid();
}
}
private void BindMyGrid()
{
gvStates.DataSource = _statesUsed;
gvStates.DataBind();
}
I then have a form to add new States. When the user adds a state, I'm trying to add it to the local _statesUsed variable, and rebind the grid. Example:
protected void btnAddState_Click(object sender, EventArgs e)
{
_statesUsed.Add(new StatesUsed { StateCode = 1, StateName = "Test" });
BindMyGrid();
}
This always fails when trying to add the new item saying "Object reference not set to an instance of an object"...
How do I keep _statesUsed persistant? The idea is to add all user input using the generic class and then update the database at one go. If you know of another way to accomplish this, I'd be very grateful.
Thanks in advance!
Instead of
private List<StatesUsed> _statesUsed;
I'm usually using something similar to:
private List<StatesUsed> _statesUsed
{
get
{
var result = ViewState["_stateUsed"] as List<StatesUsed>;
if ( result == null )
{
result = new List<StatesUsed>();
ViewState["_stateUsed"] = result;
}
return result;
}
}
I.e. I am persisting page class variables to the ViewState.
If you want to keep stuff "alive" through multiple postbacks you either have to store stuff to a database, use Session, use the Viewstate, or store it temporarily in shared server memory. Which of these you choose is dependent on your use case,
In your case I would probably add an asp:HiddenField runat="server" ID="HiddenFieldUsedStateIDs" in which I wrote the IDs comma separated whenever there is a change and then read the values into the generic list in Page_Load (on every Page_Load, not just !IsPostBack)
This would utilize the Viewstate mechanism in Asp.Net to write the values to the rendered HTML and read it back into the HiddenField's value on each post
Asuuming that your viewstate in not disabled, you could do,
protected void btnAddMat_Click(object sender, EventArgs e)
{
List<StatesUsed> temp = null;
temp = (List<StatesUsed>)gvStates.DataSource;
if(temp != null)
temp.Add(new StatesUsed { StateCode = 1, StateName = "Test" });
gvStates.DataBind();
}
Can I assign a value to a variable (int) and never lose this value inside any scope ?
the problem is I am assigning the value to the variable in some scopes but the variable returns to its default value (zero) in other scopes..
Example :
protected void Button_AddNewCourse_Click(object sender, EventArgs e)
{
ID = 10;
}
so when I am trying to use ID in other functions it falls back to zero
protected void AnotherFunction(object sender, EventArgs e)
{
// Variable ID here is zero
}
At a guess, perhaps you're a newcomer to ASP.NET and haven't figured out why page-level variables don't keep their state between postbacks. Try reading up on Session state and Viewstate
Or for a general overview: ASP.NET State Management Overview
e.g. based on your code example, you could use a Session entry to store the value:
protected void Button_AddNewCourse_Click(object sender, EventArgs e)
{
Session["ID"] = 10;
}
protected void AnotherFunction(object sender, EventArgs e)
{
int tempID = (int)Session["ID"];
}
There's lots of other things you could also do - use Viewstate, for example.
Change the line that looks similar to this (which is probably somewhere):
public int ID { get; set;}
to something like
// keep the value of ID in this page only
public int ID { get { return (int)ViewState["ID"]; } set { ViewState["ID"] = value; } }
or
// keep the value of ID in every page
public int ID { get { return (int)Session["ID"]; } set { Session["ID"] = value; } }
Maybe try using readonly variables?