Access variables after initialization in page load ASP.NET Webforms - asp.net

I have this webform:
public class web1{
private string target = string.Empty;
protected void Page_Load(object sender, EventsArgs e){
target = "something";
}
protected void btnSubmit_Click(object sender, EventArgs e){
//use target variable here
}
}
When I click the button which triggers btnSubmit_Click() the target variable gets reset to string.Empty because of private string target = string.Empty.
Currently I'm assigning the new value to a Session and clearing it after the button click, but was wondering if there was a way of avoiding Session.

This typcial would work:
private string target = string.Empty;
protected void Page_Load(object sender, EventsArgs e){
if (!IsPostBack)
{
target = "something";
ViewState["target"] = target;
}
else
target = (string)ViewState["target"];
}
Now any button click, event code, or whatever is free to use target.

Related

unable to persist data on postback in dotnetnuke7

I have my website running on dotnetnuke 7.4, i have a checklistbox which i bind on the page load, and after selecting items from it, user clicks on the submit button, the selected items should save in database, however when i click on the submit button, checklistbox gets blank, i tried to enable ViewState at :
Web.config level
Page Level
Control Level
But all in vain, it still unbinds checklistbox because of which everything disappears, i tried the same in plain .net and it works like a charm.
Is there any specific settings in dotnetnuke to support viewstate, or is there any other better option to achieve this.
Here's my code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in chkBox.Items)
Response.Write(item.Text + "<br />");
}
There's the issue. Remove that (!IsPostBack) check in your page_load event. Have your code to be like below. Else, only at first page load you are binding the datasource to control which gets lost in postback.
protected void Page_Load(object sender, EventArgs e)
{
Entities objEntities = new Entities();
List<Entities> obj = objEntities.GetList(2);
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
}
OR, to be more efficient; refactor your code to a method like below and store the data object in Session variable like
private void GetDataSource()
{
List<Entities> obj = null;
if(Session["data"] != null)
{
obj = Session["data"] as List<Entities>;
}
else
{
Entities objEntities = new Entities();
obj = objEntities.GetList(2);
}
chkBox.DataSource = obj;
chkBox.DataTextField = "Name";
chkBox.DataValueField = "ID";
chkBox.DataBind();
Session["data"] = obj;
}
Call the method in your Page_Load event like
protected void Page_Load(object sender, EventArgs e)
{
GetDataSource();
}

Update controls field when page load

I fill some controls with data from data base, by calling a select method
and I change the values to update it, but when I press update button, it takes the values that called at the page load, and ignore all changes.
how can I avoid this ?
thanks in advance : )
here is a simple code to present my problem
SelectBLL _selectbll;
string _title = string.Empty;
string _details = string.Empty;
#region Page Load
protected void Page_Load(object sender, EventArgs e)
{
GetUMedicineDetails();
}
#endregion
#region Get UMedicine Details
private void GetUMedicineDetails()
{
_selectbll = new SelectBLL();
_selectbll._GetUMedicineDetails(Request.QueryString[0].ToString(), ref _title, ref _details);
#region Bind Controls
txtdetails.Text = _details;
txttitle.Text = _title;
#endregion
}
#endregion
#region Update Button
protected void btnupdate_Click(object sender, EventArgs e)
{
_UpdateUMedicine();
}
#endregion
#region UpdateU Medicine
public void _UpdateUMedicine()
{
_updatebll = new UpdateBLL();
_updatebll._UpdateUMedicine(
Convert.ToInt32(Request.QueryString[0]), txtdetails.Text, txttitle.Text);
}
#endregion
Page.IsPostBack Property: Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetUMedicineDetails();
}
}
Also, Refer:
How to: Determine How ASP.NET Web Pages Were Invoked
DataBind only if !Page.IsPostaBack:
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostaBack)
GetUMedicineDetails();
}

Drop down selected index changed on page load

I have a drop down box that populates textbox values based on its value. It fires when it is changed but on pageload it doesnt fire. How do I get it to fire on page load?
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox3.Text = DropDownList1.SelectedValue;
TextBox12.Text = DropDownList1.SelectedValue;
TextBox21.Text = DropDownList1.SelectedValue;
//etc
Tim Schmelter's comment is right on the money.
// Wire up to the page load event
protected void Page_Load(object sender, System.EventArgs e)
{
updateTextBoxes();
}
// Wire up to the select index-changed event
protected void DropDownList1_SelectIndexChanged( object sender, EventArgs e )
{
updateTextBoxes();
}
// your workhorse method
protected void updateTextBoxes()
{
TextBox3.Text = DropDownList1.SelectedValue;
TextBox12.Text = DropDownList1.SelectedValue;
TextBox21.Text = DropDownList1.SelectedValue;
// etc.
}
It won't be called automatically at page load, you have to call it "manually":
void Page_Load(object sender, System.EventArgs e) {
// ....
DropDownList1_SelectedIndexChanged(DropDownList1, e);
}
SelectedIndexChanged fires in response to a user-driven change. Move the assignment logic to another method and call it manually from Page_Load and also from your event handler.

Passing the value of a XML tag to another page

Here is the page where I am retrieving from a XML page and by storing it in cookie, I want to retrieve it in another page.
public partial class shopping : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
HttpCookie userCookie = new HttpCookie("user");
userCookie["quantity"] = TextBox1.Text;
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("shopping_cart.xml"));
XmlNode root = doc.DocumentElement;
if (RadioButton1.Checked)
{
string str1 = doc.GetElementsByTagName("cost").Item(0).InnerText;
userCookie["cost"] = str1;
//Label3.Text = str1;
Response.Redirect("total.aspx");
}
}
}
and here is other page where I am trying to retrieve it (total.aspx.cs):
public partial class total : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
**Label2.Text = Request.Cookies["user"]["quantity"];**
}
}
I am getting a Null Reference on the line which is in bold. Any suggestions on how can I do it?
You created the cookie in the first section, but forgot to append it to the Response.
Response.Cookies.Add(userCookie); // place before your Response.Redirect
Also, be aware that cookies have a useful maximum size of 4000 bytes, and otherwise a probably not the best choice for what you are doing. You may wish to store temporary session info in the Session for access between pages, rather than use a cookie.
Session["quantity"] = TextBox1.Text
// ...
Session["cost"] = str1;
and in the second page
Label2.Text = Session["quantity"] as string;

CheckedChanged event for Dynamically generated Checkbox column in DataGrid(Asp.Net)

I have a datagrid (Asp.Net) with dynamically generated checkbox column..I am not able to generate the checkedChanged event for the checkbox..
Here is my code:
public class ItemTemplate : ITemplate
{
//Instantiates the checkbox
void ITemplate.InstantiateIn(Control container)
{
CheckBox box = new CheckBox();
box.CheckedChanged += new EventHandler(this.OnCheckChanged);
box.AutoPostBack = true;
box.EnableViewState = true;
box.Text = text;
box.ID = id;
container.Controls.Add(box);
}
public event EventHandler CheckedChanged;
private void OnCheckChanged(object sender, EventArgs e)
{
if (CheckedChanged != null)
{
CheckedChanged(sender, e);
}
}
}
and Here is the event
private void OnCheckChanged(object sender, EventArgs e)
{
}
Thanks In advance
When do you add your custom column? If it is on load, then it is too late. Load it on init. I.e. following works with your code:
protected void Page_Init(object sender, EventArgs e)
{
ItemTemplate myTemplate = new ItemTemplate();
myTemplate.CheckedChanged += new EventHandler(myTemplate_CheckedChanged);
TemplateField col = new TemplateField();
col.ItemTemplate = myTemplate;
col.ItemStyle.Wrap = false;
grid.Columns.Add(col);
}
If your checkbox ID's are not being set the same way on every postback, then they can never be connected to the event handlers when it comes time to process the events. Where is your field "id" coming from?

Resources