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

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).

Related

basic incremental on button click

I'm trying to write a simple button that when you click it adds 1 and updates the label but it only works on the first click after that it doesn't update the label anymore
protected void Page_Load(object sender, EventArgs e)
{ }
protected void ClickerButton_Click(object sender, ImageClickEventArgs e)
{
Lbl_PairsCooked.Text = CookSneaker(NumOfPairs).ToString();
}
public int CookSneaker(int num)
{
num += 1;
return num;
}
The image button i made only works on the first click...
See the snippet below on how to get it working. Most importantly you need to read on IsPostBack the link
https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.ispostback?view=netframework-4.8 to understand the difference.
public partial class _Default : Page
{
int NumOfPairs;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//this line reads the text from label, converts and assigns to NumPairs. The UI is updated on the button click which takes this new NumOfPairs.
int.TryParse(Label1.Text, out NumOfPairs);
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = CookSneaker(NumOfPairs).ToString();
}
public int CookSneaker(int num)
{
num += 1;
return num;
}
}

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.

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

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

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

How to load web user control dynamically?

This is really important question. this makes me crazy in 4 hours :( i can load UCAddX.ascx but if i click "Search in X" button not load UCSearchX user control. There are 3 button also there are 3 web user control. i want to load these 3 web user controls after clickEvents. But below method not working.How to load web user control dynamically? Click By Click (Like Tab control)
public partial class MyPage: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ViewState["controlType"] = "AddX";
if (!IsPostBack)
{
AddUserControl();
}
else
{
AddUserControl();
}
}
protected void btnAddX_Click(object sender, DirectEventArgs e)
{
ViewState["controlType"] = "AddX";
if (!IsPostBack)
AddUserControl();
else
AddUserControl();
}
protected void btnSearchX_Click(object sender, DirectEventArgs e)
{
ViewState["controlType"] = "SearchX";
if (!IsPostBack)
AddUserControl();
else
AddUserControl();
}
protected void btnUpdateX_Click(object sender, DirectEventArgs e)
{
}
void AddUserControl()
{
// plhContent1.Controls.Clear();
if (ViewState["controlType"] != null)
{
if (ViewState["controlType"].ToString() == "AddX")
{
UCAddX uc = (UCAddX)Page.LoadControl("~/Pages/EN/MyUserControls/UCAddX.ascx");
uc.ID = "ucAddX";
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
plhContent1.Controls.Add(uc);
}
else if (ViewState["controlType"].ToString() == "SearchX")
{
UCSearchX uc = (UCSearchX)Page.LoadControl("~/Pages/EN/MyUserControls/UCSearchX.ascx");
uc.ID = "ucSearchX";
uc.Attributes.Add("runat", "Server");
uc.EnableViewState = true;
uc.Visible = true;
plhContent1.Controls.Add(uc);
}
}
}
}
Use the code below to load usercontrol dynamically
var control = LoadControl(filePath) as ControlType;
then you can subscribe to events and add to control placeholder.
Hope this helps
try something like this,
//to load the control
protected void Page_Init(object sender, EventArgs e)
{
ViewState["controlType"] = "AddSector";
//you don't need to check the if condiontion, cause you load every time the controls
AddUserControl();
}
when you need to get values from the control after postback you should get it on
protected void Page_PreRender(object sender, EventsArgs args) {
//your placeholder that contains data
}
User controls when loaded dynamically need to be loaded on every Page_Load so their view state is maintained. So you need something like:
public string CurrentControlToLoad
{
get
{
if(ViewState["controlType"] == null)
return "";
return (string)ViewState["controlType"];
}
set
{
ViewState["controlType"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if(CurrentControlToLoad != "")
LoadControl(CurrentControlToLoad);
}
protected void btnAddSector_Click(object sender, DirectEventArgs e)
{
CurrentControlToLoad = "AddSector";
LoadControl(CurrentControlToLoad);
}

Categories