Introducing XDA:DevCon – A Conference For Developers By Developers
XDA Developers Android and Mobile Development Forum
Forgot your password?
 
Post Reply+
Tip us?
 
GFR_2009
Old
#1  
Member - OP
Thanks Meter 0
Posts: 37
Join Date: Oct 2009
Default [Q] How to delete/add an item from a ListBox?

Hi there,

I have a ListBox bounded to a query (linq to xml)

Dim CASDAs XDocument = XDocument.Load("./Data/CASD.xml")

Dim CAS_Query As System.Collections.IEnumerable = From query In Cartridge_Doc.Descendants("Cartridges") Order By _
CStr(query.Element("AA")) Descending, CStr(query.Element("AA"))
Select New Cartridge_Data With {.AA1 = CStr(query.Element("AA")), _
.BB1= CStr(query.Element("BB")), _
.CC1 = CStr(query.Element("CC"))}

Me.ListBox_1.ItemsSource = CAS_Query

Now, what I need to do is to select an item and have the option to delete it.

So far, I always got a run-time exception when trying this

Me.ListBox_1.Items.Remove(Me.ListBox_1.SelectedIte m)

System.InvalidOperationException was unhandled
Message=Operation not supported on read-only collection.


So far I have tried a lot of options without any luck.

Any help will be greatly appreciated!

Thanks in advance.
 
emigrating
Old
#2  
Senior Member
Thanks Meter 68
Posts: 523
Join Date: Jan 2010

 
DONATE TO ME
Stick your Linq result in an ObservableCollection, bind this to the Listbox and delete the item directly from the underlaying collection.
 
GFR_2009
Old
#3  
Member - OP
Thanks Meter 0
Posts: 37
Join Date: Oct 2009
Quote:
Originally Posted by emigrating View Post
Stick your Linq result in an ObservableCollection, bind this to the Listbox and delete the item directly from the underlaying collection.
Please, can you poost a little code to do that? I'm fairly new to this collections world.

On the other hand, once the item got deleted, how the Listbox gets refreshed?

Thanks!
 
Ren13B
Old
(Last edited by Ren13B; 27th November 2010 at 05:05 PM.)
#4  
Senior Member
Thanks Meter 19
Posts: 250
Join Date: Oct 2007
You have to set up an NotifyPropertyChanged class to keep the listbox updated with your collection. The default phone list application template that comes with Visual Studio shows you how to do this. I think its's in c# though and it looks like you're coding in VB. I'm sure there's examples in VB you can find on the web with a little searching.
 
GFR_2009
Old
#5  
Member - OP
Thanks Meter 0
Posts: 37
Join Date: Oct 2009
Quote:
Originally Posted by Ren13B View Post
You have to set up an NotifyPropertyChanged class to keep the listbox updated with your collection. The default phone list application template that comes with Visual Studio shows you how to do this. I think its's in c# though and it looks like you're coding in VB. I'm sure there's examples in VB you can find on the web with a little searching.
My ListBox takes its data from an XML file via query.

Which strategy do you think is the best?

To first delete the Xelement then refresh the ListBox?

Or deleting from the item from the ListBox, then update the XML file?

Sorry but I have all the samples from MS and didn't find any phone list one.

Any code will be greatly appreciated!
 
Ren13B
Old
#6  
Senior Member
Thanks Meter 19
Posts: 250
Join Date: Oct 2007
Oops. It's called "Windows Phone Databound Application". Attached is a screenshot of the project if it makes it easier for you to find it.

It's hard to post code because I don't know what your xaml looks like and bindings have to be set there for it to work. The best thing you can do is load the above project and play around with it.

You never have to refresh the items in the listbox. A bound listbox updates itself when an item in the collection changes. Change the collection and your listbox will reflect those changes. The NotifyPropertyChanged class is what triggers the listbox to update itself.
Attached Thumbnails
Click image for larger version

Name:	Untitled-1.jpg
Views:	41
Size:	52.1 KB
ID:	451062  
 
emigrating
Old
(Last edited by emigrating; 27th November 2010 at 09:19 PM.)
#7  
Senior Member
Thanks Meter 68
Posts: 523
Join Date: Jan 2010

 
DONATE TO ME
I do C#, not VB but the following should give you some idea.

Code:
public class Model : INotifyPropertyChanged
{
    public string Title { get; set; }
    public string Blurb { get; set; }

    public event PropertyChangedEventHandler PropChanged;
    public void NotifyPropertyChanged(String _propName)
    {
        if (null!=PropChanged)
        { PropChanged(this, new PropertyChangedEventArgs(_propName)); }
    }
}
The above is your model, create any properties you need there - i.e. one per item of data in your XML file.

Next, you need to create an ObservableCollection somewhere, for the sake of simplicity let's stick it in your MainPage.xaml.cs file for now, so;

Code:
public partial class MainPage : PhoneApplicationPage
{
    public ObservableCollection<Model> Items { get; set; }

    public MainPage()
    {
        InitializeComponent();
        this.Items = new ObservableCollection<Model>();
        MyListBox.ItemsSource = this.Items;

        WebClient wc = new WebClient();
        wc.OpenReadCompleted += wc_OpenReadCompleted;
        wc.OpenReadAsync(new Uri("http://your.server.here/datafile.xml");       
    }

    public void wc_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {
        using (Stream s = e.Result)
        {
            XDocument xd = Xdocument.Load(s);
            var XMLdata = (from q in doc.Descendants("Item") select new Model()
            {
                Title = (string)q.Element("Title"),
                Blurb = (string)q.Element("Blurb")
            }

            foreach (Model m in XMLdata)
            {
                this.Items.Add(m);
            }
        }
    }

    public MyListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ListBox lb = (ListBox)sender;
        if (lb.SelectedIndex == -1)
            return;

        this.Items.Remove(lb.SelectedItem)
    }
}
This will create a collection named Items as well as tell your ListBox (named MyListBox) to get it's data from said collection. Then it will read (asynchroniously) the XML file from the web and copy each item of data into your collection.

When you select an item in your ListBox it will be deleted from the ObservableCollection which in turn will remove it from the view (ListBox). At this stage you want to include code to also remove this from your actual XML file and so on of course. But the idea is that you work on your Collection only and your View will update based on what is changed - automagically.

Please note, the above code may or may not work out of the box. Written directly here on the forums so it hasn't gone thru VS2010's excellent IntelliSense. Also, the above code is in no way the most efficient way of doing certain things, but it gives you an idea as to what code you need to write to handle your scenario.

While I wrote this I see you've got an answer above which directs you to the VS template - use that and everything should become clear. All you have to remember is that perform operations on the Collection - not directly on the ListBox and you'll be fine.
 
GFR_2009
Old
#8  
Member - OP
Thanks Meter 0
Posts: 37
Join Date: Oct 2009
Emigrating and Ren13B,

Thanks to both of you for the help. Very appreciated!

Will take both advices to see what comes up.

Thanks!

 
Post Reply+
Thread Tools Search this Thread
Search this Thread:

Advanced Search
Display Modes

report this ad
Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Go to top of page...

XDA PORTAL POSTS

Careers in Android: What Hiring Managers Won’t Tell You – XDA Developer TV

XDA Developer TV Producer Jayce released a video a … more

Coloring Your Logcat World

Getting feedback for your app during development is as simple as adding logging info where necessary and looking … more

Guide Your Sheep to Safety with Finger Shepherd

Just a coupe of days ago, we brought you news about a game calledAgent Sheep. In that … more

Nandroid Manager Receives Major Update

Do you find yourself obsessively jumping from ROM to ROM? And do you hate having to restore a full … more