Adding and Deleting Items in List View Control in Metro Style Apps - DAY 8

Niladri.Biswas
Posted by in Windows Metro category on for Beginner level | Points: 250 | Views : 8100 red flag

In this article we will learn about adding items to ListView control and Deletion of items from ListView control


 Download source code for Adding and Deleting Items in List View Control in Metro Style Apps - DAY 8

Introduction

This is the eighth day of the learning series where we will learn about adding items to ListView control and Deletion of items from ListView control.Earlier in one of the previous tutorials, we have already explored about the List View Tutorials

Straight to experiment

Let us first create a "data.js" file where we will define our datasource as under

(function () {

    "use strict";

    var sourceData = [
                        { name: 'Mint', pic: "images/1.png" },
                        { name: 'Sauce', pic: "images/2.png" },
                        { name: 'Straberry', pic: "images/3.png" },
                        { name: 'Sauce', pic: "images/4.png" }
                  ];

    var datalist = new WinJS.Binding.List(sourceData);

    var dataMembers = { itemlist: datalist };

    WinJS.Namespace.define("SourceData", dataMembers);
})();

Next visit the "default.html" page and write the below code inside the "body" tag

<body>
    <div id="mainContent">
        <div id="divDisplayItems" data-win-control="WinJS.Binding.Template">

            <div style="width: auto; height: auto">
                <span data-win-bind="innerText:name"></span>
            </div>
            <img src="#" data-win-bind="src:pic; alt:name" />

        </div>

        <div id="basicListView" data-win-control="WinJS.UI.ListView"/>       
    </div>

    <div id="operations"> 

        <button id="btnAdd">Add Item</button>
        <button id="btnDeleteSelectedItem" style="display:none">Delete Selected Item(s)</button>

    </div>

</body>

Now let us go to the "default.js" file and write the below piece of code for populating the ListView

listView = document.getElementById("basicListView").winControl;
            WinJS.UI.setOptions(listView, {
                itemDataSource: SourceData.itemlist.dataSource,
                itemTemplate: document.getElementById("divDisplayItems")
            });

If we run at this point of time, we will get the ListView being populated with the supplied items as under

While the items is loaded the very first time, the "Delete" button is hidden (hence style="display:none").Now let us write the code for Adding items to the ListView

function AddItemsToCollection(eventInfo)
{   
	var _dataSource = document.getElementById("basicListView").winControl.itemDataSource;
		
	//Start the sequence of edits
	_dataSource.beginEdits();

	//Get new Items that will be added to the existing item source
	var newItems = GenerateNewItems();

	//Adds new item to the end of the data source.
	_dataSource.insertAtEnd(null, newItems);

	//Ends the batch of edits
	_dataSource.endEdits();

}

The WinJS.UI.IListDataSource interface provides access to ListView data source and enables us to bind, change, add, remove, and move items in that data source.It's beginEdits() method notifies the IListDataSource that a sequence of edits is about to begin.Then we are invoking the "GenerateNewItems()" method for generating new items which we are adding to the end of the existing ListView data source by using the insertAtEnd() method.And finally, while all the operations are over, we are calling the endEdits() method that notifies the IListDataSource that the batch of edits that began with the last beginEdits call has completed.

The "GenerateNewItems()" method is as under

var counter = 0;   
function GenerateNewItems()
{

	var newItems = { name: 'NewImage' + counter, pic: "images/default.png" };
	counter++;
	return newItems;
}

A simple program where we are generating an image item and incrementing the counter at each hit.If we run the application at this point of time, the below will be the output

Next we will write the program where item atleast one item is selected, then the "Delete" button will be visible.Let us invoke the below function from the ListView "selectionchanged" event

function ToggleButtonBasedOnSelectionChange(eventInfo)
{
	if (listView.selection.count() > 0) document.getElementById("btnDelete").style.display = 'inline';
	else document.getElementById("btnDelete").style.display = 'none';
}

As can be figure out that, if atleast one item is choosen, then we are displaying the button by setting it's style to "inline".

Finally let us write the code for deleting selected items

function DeleteSelectedItemsFromCollection()
{
	var _listView = document.getElementById("basicListView").winControl;

	var _dataSource = _listView.itemDataSource;

	//Proceed if atleast one item has been selected
	if (_listView.selection.count() > 0)
	{
		_listView.selection.getItems().done(function (items)
		{
			//Start the sequence of edits
			_dataSource.beginEdits();

			//Remove selected items
			items.forEach(function (item)
			{
				_dataSource.remove(item.key);
			});

			//Ends the batch of edits
			_dataSource.endEdits();
		});
	}
}

First we are checking it atleast one item has been choosen.If so, then we are removing the selected items by invoking the Remove() method which deletes the specified item from the data source.

If we need to delete all items, then set the itemDataSource property to null.

function DeleteAllItemsFromCollection()
{  
	basicListView.winControl.itemDataSource = null;
}

Conclusion

So in this tutorial, we have seen as how to add new items and remove existing items from the ListView.Experiment file is attached herewith.Thanks for reading

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)