session variables in an ASP.NET - c#

hi guy i am trying to place my session in to a drop down, any help would be great.
at the moment it puts the data in to a label, i wish to put it into a dropdown with it adding a new string every time i click button without getting rid of the last
default page
protected void Button1_Click1(object sender, EventArgs e)
{
Session["Fruitname"] = TbxName.Text; // my session i have made
}
output page
protected void Page_Load(object sender, EventArgs e)
{
var fruitname = Session["Fruitname"] as String; // my session ive made
fruit.Text = fruitname; // session used in lable
}
Have Tried
var myFruits = Session["Fruitname"] as List<string>;
myFruits.Add(listbox1.Text);
but i get error when i try to run the program
Broken glass thanks for your help, it is still not doing what i need but its getting there.
var fruitname = Session["Fruitname"] as String; // my session ive made
fruit.Text = string.Join(",", fruitname); // session used in lable
this is what is working. i need a dropdown to display all the strings put into TbxName.Text; to output into fruit

Just use a List<string> instead of a string then.
var myFruits = Session["Fruitname"] as List<string>;
myFruits.Add(TbxName.Text);

Has been fixed using code found else where
button page code bellow
protected void Button1_Click1(object sender, EventArgs e)
{
// Session["Fruitname"] = TbxName.Text; // my session i have made
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
MyFruit.Add(TbxName.Text);
Session["Fruitname"] = MyFruit;
{
public List<string> MyFruit { get; set; }
}
page where display
protected void Page_Load(object sender, EventArgs e)
{
MyFruit = Session["Fruitname"] as List<string>;
//Create new, if null
if (MyFruit == null)
MyFruit = new List<string>();
ListBox1.DataSource = MyFruit;
ListBox1.DataBind();
}
public List<string> MyFruit { get; set; }
}

Related

Reading and storing data to a list though session

When i store an item, i can store it and read it. But when i try to store another item, the first one disappear.
I'm using a masterpage for my default site dont know if it affects it.
my code is very simple and looks like this.
List<kurvliste> kurv = new List<kurvliste>();
protected void Page_Load(object sender, EventArgs e)
{
List<kurvliste> kurv = (List<kurvliste>)Session["kurv"];
if (kurv == null)
{
kurv = new List<kurvliste>();
Session["kurv"] = kurv; // Store the new list in the session object!
}
}
protected void Unnamed_ServerClick(object sender, EventArgs e)
{
kurv.Add(new kurvliste(1,1,1, "Produktnavn"));
Session["kurv"] = kurv;
}
In my masterpage it looks like this
List<kurvliste> kurv = new List<kurvliste>();
protected void Page_Load(object sender, EventArgs e)
{
List<kurvliste> kurv = (List<kurvliste>)Session["kurv"];
if (kurv == null)
{
kurv = new List<kurvliste>();
Session["kurv"] = kurv; // Store the new list in the session object!
}
Repeater1.DataSource = kurv;
Repeater1.DataBind();
}
Because you have a bug - you declare the same name outside and inside the Page_load, so on the click the outside is used - so you actually use two different lists.
I write your code adding 1 & 2 to understand the bug.
List<kurvliste> kurv_1 = new List<kurvliste>();
protected void Page_Load(object sender, EventArgs e)
{
List<kurvliste> kurv_2 = (List<kurvliste>)Session["kurv"];
if (kurv_2 == null)
{
kurv_2 = new List<kurvliste>();
Session["kurv"] = kurv_2; // Store the new list in the session object!
}
}
protected void Unnamed_ServerClick(object sender, EventArgs e)
{
kurv_1.Add(new kurvliste(1,1,1, "Produktnavn"));
Session["kurv"] = kurv_1;
}
How to solve it
But if i remove the outside, i get a null reference just by leaving it
to be List kurv.
No you need to remove the inside of Page_Load declaration that hides the outside one
protected void Page_Load(object sender, EventArgs e)
{
// on this line, just remove the declaration
// List<kurvliste> kurv = (List<kurvliste>)Session["kurv"];
// do it like
kurv = Session["kurv"] as List<kurvliste>;
if (kurv == null)
{
kurv = new List<kurvliste>();
Session["kurv"] = kurv; // Store the new list in the session object!
}
}
Alternative
I suggest to move the list on the session to a property like that
// using this const you avoid bugs in mispelling the correct key.
const string ckurvlisteNameConst = "kurvliste_cnst";
public List<kurvliste> kurv
{
get
{
// If not on the Session then add it
if (Session[ckurvlisteNameConst] == null)
Session[ckurvlisteNameConst] = new List<kurvliste>();
// this code is not exist on release, but I check to be sure that I did not
// overwrite this Session with a different object.
Debug.Assert(Session[ckurvlisteNameConst] is List<kurvliste>);
return (List<kurvliste>)Session[ckurvlisteNameConst];
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Unnamed_ServerClick(object sender, EventArgs e)
{
kurv.Add(new kurvliste(1,1,1, "Produktnavn"));
}
a similar answer : How to store list of object into ViewState

How To Delete Multiple Items from ListView C# With Delete Button

So, I have a simple ListView that users can add information to and a delete button that is only capable of deleting one selected item at a time. I'm trying to make it so that when multiple items are selected and 'delete' is pressed it deletes those selected items instead of just one. Your help is appreciated!
Add recipient code:
private void addtoRecipients_Click(object sender, EventArgs e)
{
if (recipientEmailBox.Text != "")
{
string[] S = new string[4];
S[0] = recipientEmailBox.Text;
S[1] = recipientNameBox.Text;
S[2] = txtLocation.Text;
S[3] = txtSubject.Text;
ListViewItem I = new ListViewItem(S);
recipientBox.Items.Add(I);
UpdateNoOfEmails();
}
}
My Delete Button Code (only deletes one selection at the moment)
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try { recipientBox.Items.Remove(recipientBox.SelectedItems[0]); }
catch { }
UpdateNoOfEmails();
}
Clear All Recipients Code
private void clearBTN_Click(object sender, EventArgs e)
{
recipientBox.Items.Clear();
UpdateNoOfEmails();
}
In my case, the simplest way to do it was with a while loop. This is what my new delete button code looks like:
private void deleteEntryBTN_Click(object sender, EventArgs e)
{
try
{
while (recipientBox.SelectedItems.Count > 0)
{
recipientBox.Items.Remove(recipientBox.SelectedItems[0]);
}
}
catch { }
UpdateNoOfEmails();
}

How to save a page state?

In a Windows Runtime app, I load data like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
then user can select an item from ListView:
private void ContentListView_ItemClick(object sender, ItemClickEventArgs e)
{
var selectedItem = e.ClickedItem as User;
if (!Frame.Navigate(typeof(FollowersPage), selectedItem.UserId))
{
throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
}
}
So it navigates forward to the same page, but shows new followers.
The problem is that when it navigates back, it loads data again and shows from the beginning of the list rather than showing the last item selected.
So how to save a List of data in NavigationHelper_SaveState and how to load it again in NavigationHelper_LoadState with last position in the list? thanks.
Here's a basic semi-tested example you can start from. You'll need to modify it to fit your exact circumstances. Some of it is adapted from here.
void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
var isp = (ItemsStackPanel)listview.ItemsPanelRoot;
int firstVisibleItem = isp.FirstVisibleIndex;
e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
// This must be serializable according to the SuspensionManager
e.PageState["Followers"] = this.DefaultViewModel["Followers"];
}
void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Do we have saved state to restore?
if (e.PageState != null)
{
// Restore list view items
this.DefaultViewModel["Followers"] = (WhateverType)e.PageState["Followers"];
// Restore scroll offset
var index = (int)e.PageState["FirstVisibleItemIndex"];
var container = listview.ContainerFromIndex(index);
listview.ScrollIntoView(container);
}
else
{
// Load data for the first time
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
}

Update Listbox without restarting program?

I'm building an WinForms application which is going to be an adressbook. I'm stuck with a problem though. When I open the program and press on my load contacts button, it loads all that's written in the txt file. But if I create a new contact and press load again, the new contact doesn't show up. Is there any way to fix this?
Also, when I try to create new methods for example a Delete() method. It says "Items collection cannot be modified when the DataSource property is set." Any ideas why is crashes?
List<string> Load()
{
StreamReader read = new StreamReader(path);
string row = "";
while ((row = read.ReadLine()) != null)
{
adressbook.Add(row);
}
read.Close();
return adressbook; //Adressbook is my List<string> adressbook = new List<string> uptop.
}
private void button2_Click(object sender, EventArgs e)
{
List<string> list = Load();
listBox1.DataSource = list;
}
You have to set to null the DataSource before clearing and binding:
private void button2_Click(object sender, EventArgs e)
{
if(listBox1.DataSource != null)
{
listBox1.DataSource = null;
listBox1.Items.Clear();
}
List<string> list = Load();
listBox1.DataSource = list;
}
In your Load you must first clear the list
List<string> Load()
{
if (adressbook.Count != 0)
{
adressbook.Clear();
}
StreamReader read = new StreamReader(path);
string row = "";
while ((row = read.ReadLine()) != null)
{
adressbook.Add(row);
}
read.Close();
return adressbook; //Adressbook is my List<string> adressbook = new List<string> uptop.
}

Get checkbox list values to a single string

I'm trying to get checkbox list values to a single string. in ASP.net using C#.
Here's my code.. I have declared this globally.
string hobbies = "";
This is the code to get the selected items to a string.
protected void chkListHobbies_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i=0;i<chkListHobbies.Items.Count;i++)
{
if (chkListHobbies.Items[i].Selected)
{
hobbies += chkListHobbies.Items[i].Value + ",";
}
}
hobbies = hobbies.TrimEnd(',');
I'm displaying this on button click
protected void btnEnter_Click(object sender, EventArgs e)
{
Response.Write("Hobbies= "+hobbies);
}
It doesn't give the expected output.
Would like to get this corrected if it's wrong or would like to know how to do it properly.
Thanks in advance.
You have to create hobbies list in your btnEnter_Click event handler because Asp.net webforms in stateless and you'll get a new hobbies variable after each postback. To address this issue you have to save hobbies state somehow (using viewstate or a hidden field) and use it later or as I suggested create hobbies list in btnEnter_Click.
Edit (examples):
1.Do the whole thing in btnEnter_Click:
protected void btnEnter_Click(object sender, EventArgs e)
{
string hobbies = "";
for (int i=0;i<chkListHobbies.Items.Count;i++)
{
if (chkListHobbies.Items[i].Selected)
{
hobbies += chkListHobbies.Items[i].Value + ",";
}
}
hobbies = hobbies.TrimEnd(',');
Response.Write("Hobbies=" + hobbies);
2.Use ViewState:
private string hobbies
{
get { return (ViewState["hobbies"] ?? "").ToString(); }
set { ViewState["hobbies"] = value; }
}
and the rest of your code is exactly the same.

Categories