Write Cookies and set cookies value as text box select Vlaue - asp.net

I am trying to store the selected value of a dropdown list in a cookies which work perfectly with this code.
protected void state_DropDownList_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie StudentCookies = new HttpCookie("userloaction_cookies");
StudentCookies.Value = state_DropDownList.SelectedValue;
StudentCookies.Expires = DateTime.Now.AddDays(1000);
Response.Cookies.Add(StudentCookies);
}
I then want to use the cookie value to set the select value for the dropdown list after page_load. It works, but I cannot change the dropdown value after the first value has been stored in the cookies.
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["userloaction_cookies"] != null)
{
HttpCookie aCookie = Request.Cookies["userloaction_cookies"];
string cookiesvalue = Server.HtmlEncode(aCookie.Value);
state_DropDownList.SelectedValue = Server.HtmlEncode(aCookie.Value);
}
I think the issue is that the Page_load method triggers before the state_DropDownList_SelectedIndexChanged method.
Is there any possible way of making this work?

Page load triggers first on each post back.
You will need to check the value of IsPostBack.
Here is how:
if (!IsPostBack)
{
if (Request.Cookies["userloaction_cookies"] != null)
{
HttpCookie aCookie = Request.Cookies["userloaction_cookies"];
string cookiesvalue = Server.HtmlEncode(aCookie.Value);
state_DropDownList.SelectedValue = Server.HtmlEncode(aCookie.Value);
}
}

Related

Update the data in database in asp.net

I can successfully select the data I want to update to another page and populate my text boxes but if I set the selected values to my textbox and then try to update it wouldn't work and the same data is shown in database table.
However if I DO NOT set those values to my textboxes, then I can successfully update which is not what I am after.
I would like the user to see the data and record that s being updated
Here is my code:
protected void Page_Load(object sender, EventArgs e)
{
UserClassesDataContext db= new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
TextBox1.Text = q.user_name;
TextBox2.Text = q.password;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
UserClassesDataContext db = new UserClassesDataContext();
var qr = from user in db.Users
where user.user_id == new Guid(Request.QueryString["user_id"])
select user;
foreach (var q in qr)
{
q.user_name = TextBox1.Text;
q.password = TextBox2.Text;
}
db.SubmitChanges();
Response.Redirect("Default.aspx");
}
What am I doing wrong?
Thanks
The problem is, when you submit the button, the code inside Page_Load event is executing again.That means it is reading the data from your table and setting the value to textboxes(thus overwriting what user updated via the form ) and you are updating your record with this values (original values). So basically you are updating the rows with same values.
You can use the Page.IsPostBack property to determine whether the event is occurred by a postback(button click) or initial page load.
This should fix it.
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
// to do: read and set to textbox here.
}
}

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

Call a button_click on page_load asp.net

I have a search textbox and a search button, when clicked displays a grid with the following names and gender.However I have redirected the page to another page on edit.Now When I comeback from that page to the page containing the gridview I want to display the same search again. I have successfully put retrieved the information but storing it into session, but I'm not able to call my btn_click event # page_Load.
Here's a snippet:
EDIT: I have made some changes in my code
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
if (Session["FirstName"] != null)
txtSearch.Text = Session["FirstName"].ToString();
if (Session["Gender"] != null)
ddlGen.SelectedValue = Session["Gender"].ToString();
btnSearch_Click(sender, e);
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
and here's the click event:
protected void btnSearch_Click(object sender, EventArgs e)
{
string query = "Select EmployeeId,FirstName,Password,Address,sex,Deptno,act_book,actTV,DOJ,isActiveYN from employees where 1=1";
if (txtSearch.Text != "")
{
query += " and FirstName like '%" + txtSearch.Text + "%'";
Session["FirstName"] = txtSearch.Text;
}
if (ddlGen.SelectedValue != "")
{
query += " and sex='" + ddlGen.SelectedValue.ToUpper() + "'";
Session["Gender"] = ddlGen.SelectedValue;
}
DataSet ds = new DataSet("Employees");
SqlConnection con = new SqlConnection("Password=admin;User ID=admin;Initial Catalog=asptest;Data Source=dbsvr");
SqlDataAdapter da = new SqlDataAdapter(query, con);
da.Fill(ds);
gvSession.DataSource = ds;
gvSession.DataBind();
}
Now I'm able to save search, so that problem is resolved ,but another has poped up that when I click the button search after changin text it takes me back to the older search..The reason is probably because sessions are not cleared,but I did that as well by handling textchanged and selectedindexchanged eventd.
Rather than trying to call your button click handler from the Page_Load, change your button click handler to simply call another method like:
protected void btnSearch_Click(object sender, EventArgs e)
{
RunSearch();
}
Then move all your btnSearch_Click() code into RunSearch()
Then in your Page_Load you can do something like:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Gender"] != null && Session["FirstName"] != null)
{
txtSearch.Text = Session["FirstName"].ToString();
ddlGen.SelectedValue = Session["Gender"].ToString();
RunSearch();
}
if (!Page.IsPostBack)
{
BindGrid();
}
}
On a side note, I would recommend taking a look into SQLCommand Parameters. Your code is prone to SQL Injection Attacks:
http://en.wikipedia.org/wiki/SQL_injection
You should reset the session redirected variable so it doesn't fall in the same case.
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Redirected"] != null)
{
Session["Redirected"] = null;
....
You can do using an QueryString paremeter when page return back to main page then here you can check QueryString paremeter is exist. here you can implement code for bind grid
if (Request.QueryString["Back"]!= null)
{
// Your bind grid function
}
You can create a function, which will called both from the button_click and page_load.

ViewState null on postback

So I have a listbox on my page and some textfields. Through the textfields I can add an item to my listbox (click the button, it adds it to a private List<string> which is then set as a ViewState and the list is databound again).
My listbox is also in an updatepanel which gets triggered on the button's Click event.
Problem: My Viewstate remains null on a postback so it gets reset each time.
Some code:
private List<IngredientData> _ingredientsList;
protected void Page_Load(object sender, EventArgs e)
{
// prepare ingredient lists
_ingredientsList = new List<IngredientData>();
if (Page.IsPostBack)
{
if (ViewState["IngredientsList"] != null)
{
_ingredientsList = (List<IngredientData>) ViewState["IngredientsList"];
}
}
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataTextField = "Text";
lstIngredients.DataValueField = "Name";
lstIngredients.DataBind();
}
protected void btnAddIngredient_Click(object sender, EventArgs e)
{
_ingredientsList.Add(new IngredientData { Name = txtIngredientName.Text, Quantity = txtUnitQuantity.Text, Unit = lstUnits.SelectedValue });
ViewState["IngredienstList"] = _ingredientsList;
lstIngredients.DataSource = _ingredientsList;
lstIngredients.DataBind();
}
Any idea how I can fix this? Am I doing something wrong?
btnAddIngredient_Click is adding to "IngredienstList" not "IngredientsList" (note the spelling).
You can avoid this kind of typo by using a constant:
private const string IngredientsListViewStateKey = "IngredientsList";
then referring to it like this:
ViewState[IngredientsListViewStateKey] = _ingredientsList;

Asp.NET cookies returning null

I'm trying to save a cookie when a button is clicked like so...
protected void btn_login_Click(object sender, EventArgs e)
{
HttpCookie cookie = new HttpCookie("test");
cookie["work"] = "now";
cookie.Expires = DateTime.Now + new TimeSpan(1, 0, 0, 0);
cookie.Domain = ".cookie.com";
Response.Cookies.Add(cookie);
}
Then on the page_load I am reading the cookie...
protected void Page_Load(object sender, EventArgs e)
{
string a = Response.Cookies["test"]["work"];
}
But it keeps coming back null. I am running this under localhost and I read that cookies won't save under localhost so I edited my host file to say
127.0.0.1 test.cookie.com
When I used Fiddler to see what was getting posted to the header of the page. It looks like this...
test/work = now
test =
So I can see that it is getting set but for some reason when I read it in it returns null.
On the page_load change it from Response.Cookies to Request.Cookies.
The Response object is for sending data back. The Request object has data that is passed to you.
example:
String a = Request.Cookies["test"]["work"];
Note that if the cookie doesn't exist, then this will cause a null reference exception.
Usually you should do something like:
protected void Page_Load(object sender, EventArgs e) {
HttpCookie cookie = Request.Cookies["test"];
String a = String.Empty;
if (cookie != null) {
a = cookie["work"];
}
}
Try this
Response.Cookies["work"].Value = "Value1"
Refer this for more information.
On pageload for reading the cookie try
string value = Request.Cookies["work"].Value

Resources