Using ASP.NET Cache/ViewState/Session - asp.net

I'm trying to learn about Cache, Page ViewState, and Session. I created an ASP.NET web app in VS2010 and added 3 text boxes and a button to the page. I run in debug mode, enter random text into each, press the button, and nothing seems to be saved (all text is "null", as you'll see in the code). Am I performing these action in the wrong place? Do I need to add something to the web.config? Here is the code I'm using:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
if (Cache["textbox1"] != null)
TextBox1.Text = (string)Cache["textbox1"];
else
TextBox1.Text = "null";
if (ViewState["textbox2"] != null)
TextBox2.Text = (string)ViewState["textbox2"];
else
TextBox2.Text = "null";
if (Session["textbox3"] != null)
TextBox3.Text = (string)Session["textbox3"];
else
TextBox3.Text = "null";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Cache["textbox1"] = "(Cache) " + TextBox1.Text;
ViewState["textbox2"] = "(VS) " + TextBox2.Text;
Session["textbox3"] = "(Session) " + TextBox3.Text;
}
And the page header:
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="State._Default" EnableSessionState="True" EnableViewState="True" %>
Thanks, and sorry for the rookie question. I'm very new to this.

Page_Load happens before Button1_Click. So on Page_Load you always replace textbox text with something from statebags ("null" at first and then "(Cache)" + "null" etc). What you enter in textboxes never lives until Button1_Click.
Use Page_PreRender instead.

Right now, every time you click the button, the code in your Page_Load procedure is overwriting the TextBox.Text values before the Button1_Click event gets a chance to save them.
If you change if (IsPostBack) to if (!IsPostBack), the values will only attempt to be loaded from session/viewstate/cache when you initially request the page. So you would have to request the page, set new values with the button, then re-request (Enter key in address bar) to run the code in Page_Load.
What I would suggest is you create a new button called "Load Values" whose Click event will run the code currently found in your Page_Load. That way you don't have to tie that code to whether the request was a postback or not. I think it would make your test results much easier to understand.

Related

Object reference not set to an instance of an object. This happens while adding checkboxlist control dynamically

Object reference not set to an instance of an object.
protected void cmdSave_Click(object sender, EventArgs e)
{
string strNames = string.Empty;
CheckBoxList Chkboxx = (CheckBoxList)PlaceHolder1.FindControl("Chkbox");
foreach (ListItem em in Chkboxx.Items) //-------- (Showing error)
{
if (em.Selected)
{
strNames += em.Value + ", ";
}
}
string final_name = strNames.Substring(0, strNames.Length - 2);
lblNames.Text = final_name;
}
Actually I am adding Checkbox control dynamically :
protected void ddl_varient_SelectedIndexChanged1(object sender, EventArgs e)
{
string query = "select prd_vrtyvalue_id,varient_value from tbl_ProductVariety_Value where varient='" + ddl_varient.SelectedItem.Text + "' " +
" order by varient_value asc ";
DataTable abc = new DataTable();
SqlDataAdapter ada = new SqlDataAdapter(query, new CommonClass().connection());
ada.Fill(abc);
ChkboxList.ID = "Chkbox";
for (int i = 0; i < abc.Rows.Count; i++)
{
ChkboxList.Items.Add(new ListItem(abc.Rows[i]["varient_value"].ToString(), abc.Rows[i]["prd_vrtyvalue_id"].ToString()));
}
ChkboxList.RepeatColumns = 2;
PlaceHolder1.Controls.Add(ChkboxList);
}
Can Anybody tell me, what exactly i am doing wrong !
The way ASP.NET WebForms work is that the entire page is re-built during each post back. So, I imagine this is what is occuring:
Page gets "built" and includes only controls defined within your ASCX/ASPX file.
User clicks on DDL_VARIENT checkbox and the ChkboxList is added to PlaceHolder1
Form is rendered back to the user so they can see ChkboxList
Save button is clicked, causing another postback.
Page is re-built, setting all the controls back to what is defined within your ASPX/ASCX code. This does not include ChkboxList.
Your code is hit, ChkboxList no longer exists and you get your problem.
To fix, you could re-add your ChkboxList on Page_Load depending on the value of your DDL_VARIENT checkbox. If I were you though, I'd be tempted to define the ChkboxList within your ASPX/ASCX code and then set the visibility of the list depending on the value of the DDL_VARIENT checkbox within Page_Load.
I should add, the entire of the above is dependant upon you using ASP.NET WebForms. If you're using MVC then it's probably wrong.

Retain textbox values on page refresh

I have a textbox in a user control uc1. I have embedded this uc1 in a page called default.aspx. My issue is after running the application and entering some data in the textbox, when refresh the page i would like to show the values that i have entered in the textbox and not clear the textbox. I would like help with code on how to achive this. Thanks in advance for your help.
Create a global variable at the top of your aspx.cs page:
public string textboxValue
{
get
{
if (ViewState["textboxValue"] != null)
return ViewState["textboxValue"].toString();
else
return "";
}
set
{
ViewState["textboxValue"] = value;
}
}
Then, in PageLoad(), assign textboxValue a value:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
textboxValue = MyTextBox.Value;
else
MyTextBox.Value = textboxValue;
}
You can also use textboxValue to assign the value of MyTextBox at any time, or use it in any other way that might be useful to you.
The default behavior for all asp.net server side controls (runat="server") is to maintain their state. If your textbox is being cleared when your page refreshes, you are likely clearing that value yourself in code.
Are you dynamically adding the textbox or user control? If so, are you doing that during PageInit? Adding them later may cause them to lose state.
I was able to refresh the page without clearing the value in textbox. I did it as below:
I created a public property in the UC1.vb as below:
Public Property textbox_value() As String
Get
If Session("textbox1") IsNot Nothing Then
Return Session("textbox1").ToString()
Else
Return ""
End If
End Get
Set(value As String)
Session("textbox1") = value
End Set
End Property
And in the page_load event of the user control i added the code below:
If IsPostBack Then
textbox_value= textbox1.Text
ElseIf Not IsPostBack Then ' First time the page is loaded or when the page is refreshed
textbox1.Text = textbox_value
End If
Hope it helps.

ReportViewer.Find not working

I have a textbox, and a link button. On the same page I have a reportviewer.
The reportviewer is in updatepanel with linkbutton as async postback trigger.
I'm trying to find string (entered in textbox) in the report; when linkbutton is hit.
protected void lbtnFind_Click(object sender, EventArgs e)
{
ReportViewer1.Find(txtSearch.Text.Trim(), 1);
}
But that line gives error: Some parameters or credentials have not been specified Please help.
If txtSearch is a control you added, it will not be inside ReportViewer1.
If txtSearch is a control inside your ContentTemplate you should be searching in that control as follows:
var txtSrch = (TextBox)myUpdatePanel.ContentTemplate.Controls.FindControl("txtSearch");
You can get the text value from there and then set the parameters for the ReportViewer1 and refresh it.
ReportParameter[] parameters = new ReportParameter[1];
parameters[0] = new ReportParameter("Search", txtSrch.Text);
ReportViewer1.LocalReport.SetParameters(parameters);
ReportViewer1.RefreshReport();

cannot modify asp login in page_load or page_init

So I have an asp:Login field on my login page.
However, I want to use a path for the create account url and the forgot password url. So I have to do it in Page_Load or maybe Page_Init. Regardless, neither option works, it simply refuses to modify the login form.
protected void Page_Load(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.PasswordRecoveryUrl = forgotpath;
lgnMain.InstructionText = "test";
lgnMain.Focus();
}
protected void Page_Init(object sender, EventArgs e)
{
string accountpath = Request.Url.AbsoluteUri + "/user/RequestAccount.aspx";
string forgotpath = Request.Url.AbsoluteUri + "/user/ForgotPassword.aspx";
lgnMain.CreateUserUrl = accountpath;
lgnMain.UserName = "test";
lgnMain.InstructionText = "test";
lgnMain.PasswordRecoveryUrl = forgotpath;
}
The CreateUserUrl and the PasswordRecoveryUrl are ignored if you haven't set the CreateUserText and PasswordRecoveryText properties respectively. Since the Text properties probably don't need to be dynamic, just set them in the ASPX (although you could still set them in the code behind if required), and then the dynamic setting of the URL properties (in the Page_Load event) should work without problem.
Documentation here: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login_members(v=vs.85).aspx
From the Documentation above:
If the CreateUserText property is
empty, the link to the registration
page is unavailable to the user.
If the PasswordRecoveryText property
is empty, the link to the password
recovery page is not available to the
user.
have you tried setting it in the markup?
<asp:Login id="lgnMain" runat="server"
CreateUserText="Register"
CreateUserUrl="~/user/RequestAccount.aspx"
PasswordRecoveryText = "Forgot Password"
PasswordRecoveryUrl = "~/user/ForgotPassword.aspx" >
</asp:Login>

ASP .Net Passing value from gridview using Session State (VB)

I am classic asp programmer that is learning .net. Here is my problem:
I have a gridview with the following columns: Pkey, Name, Address. Lets say that I want to have a hyperlink on the Pkey field to pass that value to another page. I have been able to get this to work using querystrings. I would like to use session state to do this. I really don’t have any idea how to do this since the pkey is in the gridview. Any help would be appreciated.
Try this code :
First Page
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var firstCell = e.Row.Cells[0];
firstCell.Controls.Clear();
firstCell.Controls.Add(new HyperLink { NavigateUrl = "secondpage?pkey = " + firstCell.Text, Text = firstCell.Text, Target = "_blank" });
Session["PKEY"] = firstCell.Text;
}
}
Second Page :
string pkey = Convert.ToString(Session["PKEY"]);
label1.Text = pkey;

Resources