How to save a page state? - c#

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

Related

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

Why do you close the app when I change the page?

I have two List <>.
List<Musei> ListMusei;
List<Regioni> reg;
the object "Musei" has the property "Paese", while the object "Regioni" has the property "NomeProvincia".
The List "reg" is inserted in a ListView, and when pressed on an item, this method is invoked:
private void Listviewcitt_ItemClick(object sender, ItemClickEventArgs e)
{
var result = ((Regioni)e.ClickedItem).NomeProvincia.ToString();
var filtro = ListMusei.Where(x => x.Paese.Equals(result));
try
{
Frame.Navigate(typeof(PageAroundMe), filtro);
}
catch(Exception)
{
}
}
application where I always closes. I thought there was some problem in the "AroundMe", and then paste the code here:
In Page AroundMe I do this:
List<Musei> ListMusei;
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
ListMusei = (List<Musei>) e.Parameter;
List<Pushpin> push = new List<Pushpin>();
foreach (Musei SingoloMuseo in ListMusei)
{
Pushpin Pushpin pushpin1 = new ();
GeoPoint posizioneP;
try
{
MapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync (SingoloMuseo.Indirizzo, null);
posizioneP result.Locations.FirstOrDefault = ().Point;
pushpin1.Name = SingoloMuseo.NomeMuseo;
pushpin1.Location = posizioneP;
push.Add (pushpin1);
}
catch (Exception)
{
continue;
}
}
Where is the problem? I can not even figure out where I will close
You can pass the parameter like
Frame.Navigate(typeof(PageAroundMe), filtro.ToList());
The invalid cast exception occurs because you are trying to cast IEnumerable type to List.

session variables in an ASP.NET

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

The object cannot be deleted because it was not found in the ObjectStateManager #2

I get the problem in the screenshot:
Here is the code at the beginning of the program:
public MainWindow()
{
InitializeComponent();
BlackoutDates();
variables.date = Convert.ToDateTime(MainCalendar.DisplayDate);
DateOutput.Content = MainCalendar.DisplayDate.DayOfWeek + ", " + MainCalendar.DisplayDate.ToShortDateString();
}
//initialises entities
WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
private Booking ObjectIndex;
Here is the code when the window is loaded
private void Bookings_Loaded(object sender, RoutedEventArgs e)
{
WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
// Load data into Rooms.
var roomsViewSource = ((CollectionViewSource)(this.FindResource("roomsViewSource")));
var roomsQuery = this.GetRoomsQuery(allensCroftEntities1);
roomsViewSource.Source = roomsQuery.Execute(MergeOption.AppendOnly);
}
Here is the code for the delete button which causes the error:
private void btnDelete_Click(object sender, RoutedEventArgs e)
{
//prevents user trying to delete nothing/unselected row
if (ObjectIndex == null)
{
MessageBox.Show("Cannot delete the blank entry");
}
else
{
//deletes object from dataset, saves it and outputs a message
allensCroftEntities1.DeleteObject(ObjectIndex);
allensCroftEntities1.SaveChanges();
MessageBox.Show("Booking Deleted");
}
}
Here is the code for the object index:
private void listrow_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//outputs index of the selected room
ObjectIndex = listrow.SelectedItem as Booking;
}
EDIT,
i tried
allensCroftEntities1.Attach(ObjectIndex);
EDIT,
When i comment out the entities in the bookings loaded event, I get this error, this code used to work fine, but i dont know why all of these problems are occurring.
Try attaching entity to the context first:
allensCroftEntities1.Attach(ObjectIndex);
allensCroftEntities1.DeleteObject(ObjectIndex);
Or use context declared in class scope instead of local one within Bookings_Loaded event handler by deleting that line:
WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();

Save data for UserControl to ViewState

At my user-control I populate listbox with collection and want save data in viewstate\controlstate for further autopostback using.
protected void btFind_Click(object sender, EventArgs e)
{
var accounts = new AccountWrapper[2];
accounts[0] = new AccountWrapper { Id = 1, Name = "1" };
accounts[1] = new AccountWrapper { Id = 2, Name = "2" };
lbUsers.DataSource = accounts;
lbUsers.DataBind();
ViewState["data"] = accounts;
}
ListBox is populated at button click. When I save accounts to ViewState listBox is empty, when not it displays collection good. What's reasonn of this behaviour?
After your button is being clicked, PostBack occurs and ListBox loses it's state.
void lbUsers_DataBinding(object sender, EventArgs e)
{
if (this.IsPostBack &&)
{
AccountWrapper[] accounts = this.ViewState["data"] as AccountWrapper[];
if (accounts!= null)
{
lbUsers.DataSource = accounts;
lbUsers.DataBind();
}
}
}
(don't forget to subscribe to DataBinding event of your ListBox in markup)
Also I recommend you to encapsulate your access to ViewState:
private AccountWrapper[] Accounts
{
get { return this.ViewState["data"] as AccountWrapper[]; }
set { this.ViewState["data"] = value;
}

Categories