c# asp.net object reference lost - c#

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);
}

Related

Global Variable loses its value after page index changed in DataGrid

My problem is losing value.I have a DataGrid with standart asp.net pagination. When I change page index, global variable named "id" loses its value. Help me Please.
int id = 0;
void Payments()
{
radioBtnList = GetData();
radioBtnList.DataBind();
}
protected void Page_Load(object sender, EventArgs e)
{
Payments();
Response.Write(id); // I get value 0 :(
}
protected void radioBtnList_Changed(object sender, EventArgs e)
{
id = int.Parse(radioBtnList.SelectedItem.Text);
}
protected void dgw_pagechange(object source, DataGridPageChangedEventArgs e)
{
dgw.CurrentPageIndex = e.NewPageIndex;
dgw.DataBind();
}
Instead of storing the ID in the page which will be reloaded when the page changes you should store it somewhere that will persist over the postback.
Examples might be:
The session object
A database
A text file
You can use ViewState like this.
int id = 0;
void Payments ()
{
radioBtnList = GetData();
radioBtnList.DataBind ();
}
protected void Page_Load (object sender, EventArgs e)
{
Payments();
Response.Write(ViewState["id"]);
}
protected void radioBtnList_Changed (object sender, EventArgs e)
{
id = int.Parse (radioBtnList.SelectedItem.Text);
ViewState["id"]=id;
}
protected void dgw_pagechange (object source, DataGridPageChangedEventArgs e)
{
dgw.CurrentPageIndex = e.NewPageIndex;
dgw.DataBind();
}

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 go back to the previous page on ASP.Net and C#

Imagine I have a button which has " OnClick="GoBack" " I want it to go to the previous page, how will C# function code look like?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["RefUrl"] = Request.UrlReferrer.ToString();
}
}
protected void GoBack_Click(object sender, EventArgs e)
{
object refUrl = ViewState["RefUrl"];
if (refUrl != null)
{
Response.Redirect((string)refUrl);
}
}

Trying to add a listbox and a checkbox items

When I attempt to have CheckBoxList1.SelectedItem.Value, it gives me errors. I am a bit confused and looking through this Murach ASP.Net book but I do not see any answers. I am wanting to have what is selected in my ListBox and what is selected in my CheckBox and have them added. Any help?
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
int ucost = int.Parse(DropDownList1.SelectedItem.Value);
int ccost = int.Parse(//what does in here???);
ttbox.Text = ccost.ToString();
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
TextBox4.Text = "";
ttbox.Text = "";
}
protected void ttbox_TextChanged(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged1(object sender, EventArgs e)
{
}
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
This is a an update. They say a picture is worth a thousand words.
If you want to get all selected checkbox, you can use:
var selected = CheckBoxList1.Items.Cast<ListItem>().Where(x => x.Selected).ToList();
If you want to get only count of selected:
var count = CheckBoxList1.Items.Cast<ListItem>().Count(x => x.Selected)
If you want to get last or first element, you can use First or Last linq methods.

LINQ select return type

in my domain service class i want to return part of my object but returns nothing.
Silverlight code:
private void button2_Click(object sender, RoutedEventArgs e)
{
LoadOperation<Employees> loadOpKKM = this._employeeContext.Load(this._employeeContext.GetEmployeesById2Query(1));
loadOpKKM.Completed += new EventHandler(loadOpKKM_Completed);
}
void loadOpKKM_Completed(object sender, EventArgs e)
{
MessageBox.Show(loadOpKKM.Entities.Count().ToString());
}
Domain service class:
public IQueryable<Employees> GetEmployeesById2(int employeeId)
{
var query = from s in ObjectContext.Employees
where (s.EmployeeID == employeeId)
select new Employees()
{
Address = s.Address
};
return query;
}
where am I doing wrong?
As Silverming, GertArnold said you should first check if your table is correctly set.
private void button2_Click(object sender, RoutedEventArgs e)
{
LoadOperation<Employees> loadOpKKM = this._employeeContext.Load(this._employeeContext.GetEmployeeByIDQuery(1));
loadOpKKM.Completed += new EventHandler(loadOpKKM_Completed);
}
void loadOpKKM_Completed(object sender, EventArgs e)
{
MessageBox.Show(loadOpKKM.Entities.Count().ToString());
}
[Query(IsComposable=false)]
public Employees GetEmployeeByID(int employeeID)
{
return this.ObjectContext.Employees.Single(c => c.EmployeeID == employeeID);
}
Review your domain service to see if you didn't do any errors or typo
You should not be able to access loadOpKKM inside loadOpKKM_Completed as shown. It is outside the scope of that method (and should not compile unless you have another property of the same name).
I am guessing you are actually accessing another property called loadOpKKM on your page (which will be empty as it is not the temporary one loaded). Check your designer file for that page and see if you also have a property/control called loadOpKKM.
If not please list all the code for the page (including designer file).
as #Hitech Magic said, loadOpKKM is outside the scope of that method.
try use it like this :
private void button2_Click(object sender, RoutedEventArgs e)
{
LoadOperation<Employees> loadOpKKM = this._employeeContext.Load(this._employeeContext.GetEmployeeByIDQuery(1));
loadOpKKM.Completed += new EventHandler(loadOpKKM_Completed);
}
void loadOpKKM_Completed(object sender, EventArgs e)
{
LoadOperation<Employees> loadOpKKM = (LoadOperation<Employees>)sender;
if(loadOpKKM != null)
{
MessageBox.Show(loadOpKKM.Entities.Count().ToString());
}
else
{
//TODO
}
}

Categories