can't access instantiated object c#/asp.net - c#

I have an application that's instantiates an object from a class called "SecretNumber" when a get of the page is done. After that, I want to work with the object that's instantiated instead of instantiating a new one.
Below is a piece of my code from the code behind-file, and the problem is that I can't use the object reference inside the button function. I get an error telling that the name doesn't exist in the current context.
How can this be solved? Thanks in advance!
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
SecretNumber guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid) {
return;
}
else {
var guessedNr = int.Parse(inputBox.Text);
var result = guessNr.MakeGuess(guessedNr); <- The name 'guessNr' does not exist in the current context
}
}
}

Move declaration of the variable out of the scope of the method, so it becomes a private field of the type _Default.
This shall work
public partial class _Default : System.Web.UI.Page
{
private SecretNumber guessNr;
protected void Page_Load(object sender, EventArgs e) {
guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid) {
return;
}
else {
var guessedNr = int.Parse(inputBox.Text);
var result = guessNr.MakeGuess(guessedNr); <- The name 'guessNr' does not exist in the current context
}
}
}

SecretNumber guessNr = new SecretNumber();
Isn't actually doing anything. You need:
public partial class _Default : System.Web.UI.Page
{
private SecretNumber guessNr;
protected void Page_Load(object sender, EventArgs e) {
this.guessNr = new SecretNumber();
}
protected void btnCheckNr_Click(object sender, EventArgs e) {
if (!Page.IsValid) {
return;
}
else {
var guessedNr = int.Parse(inputBox.Text);
var result = this.guessNr.MakeGuess(guessedNr);
// Now use result
}
}
}

Put guessNr outside of Page_Load if you want to access it in btnCheckNr.
SecretNumber guessNr;
and then assign it in Page_Load Method.

I assume that you need to read some basic info about classes in C# (fields, methods, events). This isn't an ASP.NET problem because ASP.NET follows exactly the same paradigm as any other .NET technology in terms of OOP.
Obviously you need to use the field of type SecretNumber here

Related

not need to use Viewstate to retain state in asp.net?

I saw some code using Viewstate to retain state between user requests, below is the code to use a button to increment the number in a textbox input:
public partial class WebForm1 : System.Web.UI.Page
{
int ClicksCount = 1;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if(ViewState["Clicks"] != null)
{
ClicksCount = (int)ViewState["Clicks"] + 1;
}
TextBox1.Text = ClicksCount.ToString(); ;
ViewState["Clicks"] = ClicksCount;
}
}
But I don't need to use Viewstate to achieve the same goal, and it is much more simple, here is my code:
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TextBox1.Text = "0";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int i = Int32.Parse(TextBox1.Text);
i++;
TextBox1.Text = i.ToString();
}
}
so what's wrong with my code
There is nothing wrong with your code: the contents of the ASP.NET controls (as is the TextBox1 in your example) are already integrated in the ViewState automatically, and hence there is no need to manually enter them. You would use directly the ViewState to store anything that is not part of your design components (for instance an int variable that you want to increase each time).

How can I pass a string from an onclick event to another class

I am new to encapsulation. I would like to pass a string from the OnClick event of one of my buttons to a private method in another class. When I try to set the string from inside the method now it says that variable isn't recognized How can I safely pass it in?
My OnClick Event:
public partial class ClassOne
protected void lnkbtnKeySearch_Click(object sender, EventArgs e)
{
string myNewString = "Change the value of the string";
}
Class I want to pass it into:
public partial class ClassTwo
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
{
string filterText = myNewString;
}
}
You can try to hold the value of the string inside a session variable:
protected void lnkbtnKeySearch_Click(object sender, EventArgs e)
{
Session["myNewString"] = "Change the value of the string";
}
private void LoadData()
{
string filterText = Session["myNewString"].ToString();
}
One way is to make MyNewString static.
public partial class ClassOne
{
public static string MyNewString{set;get;}
protected void lnkbtnKeySearch_Click(object sender, EventArgs e)
{
MyNewString= "Change the value of the string";
}
}
Then
public partial class ClassTwo
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
{
string filterText = ClassOne.MyNewString;
}
}
}

Variable Scoping in c#.net

Hi it might sound a simple task but i am a bit confused here
I have an event :
private void ManReg_Click(object sender, EventArgs e)
{
int store = data[0];
}
and then another event function like :
private void measurementsRead_Click(object sender, EventArgs e)
{
}
I would like to use the variable "store" in the second function. How can I ?
The form is declared as follows :
namespace myRfid
{
public partial class Form1 : Form
{
}
}
You should put variable onto the class level
class ...
{
private int store;
private void ManReg_Click(object sender, EventArgs e)
{
store = data[0];
}
private void measurementsRead_Click(object sender, EventArgs e)
{
// use store
}
}
You can set it as shown in below code in your class but private as it would be used within class only as shown below :-
private int store;
private void ManReg_Click(object sender, EventArgs e)
{
this.store = data[0];
}
private void measurementsRead_Click(object sender, EventArgs e)
{
this.store//// however you want to use
}

NullReferenceException error in ASP.Net

In the below code I am getting a Null Reference Exception error while using "Names.Add(string)" method. But when I use a static class or a static object of the NamedDB class it works fine. Can any one explain how object instances work in ASP.Net web applications ? Why am I getting errors in nonstatic objects while static objects are working fine ?
public partial class _Default : System.Web.UI.Page
{
NameDB Names; //Creating Object
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Names = new NameDB();//Instantiation
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Names.Add("dss");//Object Reference is null
GridView1.DataSource = Names.GetName();
GridView1.DataBind();
}
}
//NamedDB class
public class NameDB
{
List<string> Names=new List<string>();
public void Add(string item)
{
Names.Add(item);
}
public string Remove(string item)
{
Names.Remove(item);
return item;
}
public List<string> GetName()
{
return Names;
}
}
You do not have instances of global object which are instantiated before post back. Instantiate the object again in Button1_Click
Now You would be expecting the collection to hold data between post back but you wont get it until you store it some where like database, files,session, viewstate or cache for data. Session and ViewState are not meant for storing that type of data though.
protected void Button1_Click(object sender, EventArgs e)
{
Names = new NameDB();//Instantiation
Names.Add("dss");//Object Reference is null
GridView1.DataSource = Names.GetName();
GridView1.DataBind();
}
Replace this:
NameDB Names; //Creating Object
by this
NameDB Names = new NameDB(); //Creating Object
You can do any of following
public partial class _Default : System.Web.UI.Page
{
NameDB Names= new NameDB();//Creating Object
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Names.Add("dss");
GridView1.DataSource = Names.GetName();
GridView1.DataBind();
}
}
or
public partial class _Default : System.Web.UI.Page
{
NameDB Names;//Creating Object
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Names = new NameDB();//Instantiation
Names.Add("dss");
GridView1.DataSource = Names.GetName();
GridView1.DataBind();
}
}
The problem is that the page-object is recreated for every request. So page-level fields are re-initialized for every call. And a postback is just another request!
If you want to persist values between requests, you need to find some way to store these.
Some options are:
In a real database, takes some work but you have full control and full persistence
In Cache or Application, for application-wide storage where every visitor gets the same values, but these are lost when the app recycles.
In Session, for user-specific storage as long as the session doesn't time out (and the app doesn't recycle)
In ViewState, for "postback-specific" storage: this will keep values through postbacks to the same page (user-specific), but are lost when the user goes to another page.

c# asp.net object reference lost

hello i m doing a very simple Asp.net application project
namespace WebApplication1
{
public partial class WebUserControl1 : System.Web.UI.UserControl
{
market m = new market();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void button_clickSell(object sender, EventArgs e)
{
float price = float.Parse(this.BoxIdPrezzo.Text);
m.insertProd("xxx", 10, "yyy");
m.addOfferForProd("ooo", 5, "gggg");
m.insertProd(this.BoxIdDescrizione.Text,price,this.BoxIdUtente.Text);
String s;
m.outMarket(out s);
this.Output.Text = s; //the output here work good
this.Output.Visible = true;
}
protected void button_clickView(object sender, EventArgs e)
{
String s;
m.outMarket(out s);
this.Output.Text = s; // here seem to have lost the reference to product why?
this.Output.Visible = true;
}
}
}
the problem is that when i click on button1 which call button_clickSell everything works good but when i click on button2 which call button_clickView products seem to not be anymore in the Market object, but this is pretty strange because in market object i have a list of product and m.outMarket in the first time work propely.
That is because of how pages work. Every time you make a request or a post-back to the page the values will be lost in that variable.
You will need to hold that in a session or something similar.
Here is a very basic example of using a session.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Collection"] == null)
{
Session["Collection"] = new List<int>();
}//if
}
protected void button_clickSell(object sender, EventArgs e)
{
List<int> collection = (List<int>)Session["Collection"];
collection.Add(7);
collection.Add(9);
}
protected void button_clickView(object sender, EventArgs e)
{
List<int> collection = (List<int>)Session["Collection"];
collection.Add(10);
}
you can view this post on MSDN: ASP.NET Session State Overview
Session should be used when information is required across the
pages. Now the matter for the two buttons lying on the same page. So
ViewState is Best option.
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["Collection"] == null)
{
ViewState["Collection"] = new List<int>();
}//if
}
protected void button_clickSell(object sender, EventArgs e)
{
List<int> collection = (List<int>)ViewState["Collection"];
collection.Add(7);
collection.Add(9);
}
protected void button_clickView(object sender, EventArgs e)
{
List<int> collection = (List<int>)ViewState["Collection"];
collection.Add(10);
}

Categories