Find Multiple Selected ListView Item Indices in UWP App - c#

I have a ListView named sandwichToppings which displays various sandwich toppings and allows the user to select multiple. In my controller code, I must capture the selected toppings by their index in the ListView, and send those indices back using an array.
The code which causes me to stumble is visible below. I have not been able to figure out the part which captures one or more toppings to the sandwich (the rest works fine).
void readSandwichSelection()
{
int[] toppings = null;
// One or many toppings were added to the sandwich.
if(toppingsAvailable.SelectedItems.Count > 0)
{
toppings = new int[toppingsAvailable.SelectedItems.Count];
int toppingIndex = 0;
for(int i = 0; i < toppingsAvailable.Items.Count; i++)
{
ListViewItem test = (ListViewItem)toppingsAvailable.Items.ElementAt(i);
if(test.IsSelected == true)
{
toppings[toppingIndex] = i;
toppingIndex++;
}
}
}
// No sandwich topping.
else
{
order.addSandwich(sandwichesAvailable.SelectedIndex + 1);
}
}
Along my journey, I have tried a couple solutions found on Telerik. The first:
foreach (ListViewDataItem item in radListView1.SelectedItems)
{
int example = radListView1.Items.IndexOf(item);
}
The above example fails to work because
ListViewDataItem does not exist.
When replaced by ListViewItem, a run-time error occurs: System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'Windows.UI.Xaml.Controls.ListViewItem'.'
The second attempted solution:
for (int i = 0; i < radListView1.Items.Count; i++)
{
if (this.radListView1.Items[i].Selected)
{
int example = i;
}
}
This solution cannot work because the .Selected property simply does not exist.
In all my hour of attempted work, I come up with either of these two problems. Either some form of cast exception occurs, or it is impossible to reach the property.
In my example above, I did have success in reaching the isSelected property by making a copy of each list item, and testing whether it had been selected. However, although Visual Studio lets me make the assignment
ListViewItem test = (ListViewItem)toppingsAvailable.Items.ElementAt(i);
this statement cannot run at compile time, causing an error as written previously. Which datatype other than ListViewItem must be used to count over list view items?
toppingsAvailable.SelectedItems will return a List<> of selected items. However, how could I know from this list which list index selected items belong to?

You can try the following code to get the selected toppings's indexes and put the indexes in an array. The indexes will be saved in the ToppingArray.
void readSandwichSelection()
{
int[] ToppingArray = new int[toppingsAvailable.SelectedItems.Count];
for (int i = 0; i < toppingsAvailable.SelectedItems.Count; i++)
{
var selectedIndex = toppingsAvailable.Items.IndexOf(toppingsAvailable.SelectedItems[i]);
ToppingArray[i] = selectedIndex;
}
}

Please try the following. It is Selected rather than IsSelected.
for (int i = 0; i < toppingsAvailable.Items.Count; i++)
{
var test = toppingsAvailable.Items[i];
if (test.Selected)
{
toppings[toppingIndex] = i;
toppingIndex++;
}
}

Related

Changing an FSharpList in C#

FSharpList<FSharpList<int>> newImageList;
FSharpList<int> row;
for(int i = 0; i < CurrentImage.Header.Height)
{
row = PPMImageLibrary.GrayscaleImage(CurrentImage.ImageListData);
newImageList.Head = row;
}
Above I'm trying to take a int list list and set each index to row which is a int list. Obviously I can't do it with .Head, and if I could it would only change the first index. I'm wondering how I could possibly make this work, I'm having a hard time getting any index of newImageList in the first place.
FSharpList is an immutable list. Therefore you cannot assign its Head and Tail properties something. However, you can try adding your FSharp list into a generic C# List or any collection that inherits an IEnumerable. For example from your code:
List<int> newImageList = new List<int>();
for(int i = 0; i < CurrentImage.Header.Height)
{
newImageList.AddRange(PPMImageLibrary.GrayscaleImage(CurrentImage.ImageListData)); // I am assuming your GrayscaleImage method might return multiple records.
}
I hope this helps.

Copy entire column from listview to another listview with same column format

I am trying to have 2 listviews that in the end will act as mirrors of each other. In the first listview I am able to populate it from a DB with no issues. I have another list view that when a row is checked in the first listview(listVariants) the user can move the entire row to the second listview (addFCList). With the code below it is working, sort of. The issue I am having is when another item is checked from listVariants, the way it is added to addFCList is inline and it just wraps. each item and subitem is being added to the listview as an individual item.
I have both listview cloumns setup the same. My question is how to I get the second listview(addFCList) to be the same as the the first listview(listVariants)? Am I missing something obvious...
EDIT I have solved this but will leave it here to help someone out in the future.
for (int i = 0; i < listVariants.Items.Count; i++)
{
if (listVariants.Items[i].Checked)
{
string UNI = listVariants.Items[i].SubItems[9].Text;
bool nameInsert = true;
for (int t = 0; t < addFCList.Items.Count; t++)
{
if (addFCList.Items[t].SubItems[9].Text == UNI)
{
nameInsert = false;
break;
}
}
if (nameInsert)
{
addFCList.Items.Add((ListViewItem)listVariants.Items[i].Clone());
}
}
}
Thanks for any help and suggestions.
listView1.Columns.AddRange((from ColumnHeader item in listView2.Columns
select (ColumnHeader)item.Clone()).ToArray());

How do you select multiple items in ListView from code

I am working with the new Windows 8 ListView-control. I have a list of users which are selected, depending on another list of users stored elsewhere.
Perhaps my situation is a bit specific, but my question is quite simple:
How do I select several items in a ListView-object from code?
Yout list view has property called Items
yourList.Items
This is a Collection of your items that are bind to the List. If you know indexes (or other uniq value) you can find them. If you have a list of indexes just take each from the list
yourList.Items.ElementAt(index);
If you know an Id or Name of your item or other field you can make a loop where you`ll seek them in Items collection
You can use the .SelectedItems property. Here is a simple example that fills a listview then marks the items at index 4 and higher:
for (var i = 0; i <= 10; i++)
{
if (mylistview.Items != null) mylistview.Items.Add("Item at index "+i);
}
if (mylistview.Items != null)
{
for (var i = 0; i <= mylistview.Items.Count - 1; i++)
{
if (i > 4)
{
mylistview.SelectedItems.Add(mylistview.Items[i]);
}
}
}

Finding an item in asp.ListView with Value when paging is enabled

I'm trying to find the selected Item in an aspx ListView that is on a separate page, then switch the page and select the item. I have the value property of the ListViewItem I am looking for, but cannot seem to get it to work. Here is what I tried:
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectItem(i);
break;
}
}
So lvProject is my list view. The project Variable is an Int64 which represents the UID of my Project. This is also the Value of my ListViewItems. The problem with the code above is that when paging is enabled, and the item is on a different page this will not work because the listView.Items.Count is set to the # of Items on the current page only.
My goal is to find the item, set the listview to display the correct page, and finally select the item. You would figure that I could just set the SelectedValue property, but this is not that simple as it is read only. Any ideas would help greatly, thanks in advance.
--Roman
In order to get the total record count from the object data source, you should use the Selected event as follows:
protected void ObjectDataSource1_Selected(object sender, ObjectDataSourceStatusEventArgs e)
{
// Get total count from the ObjectDataSource
DataTable dt = e.ReturnValue as DataTable;
if (dt != null) recordCount = dt.Rows.Count; // recordCount being declared outside the method
}
You would then be able to search for the item as follows:
for (int i = 0; i < recordCount; i++)
{
Label lblItem = (Label)lvProject.Items[i].FindControl("IdLabel");
if (lblItem.Text.Equals(itemToSearch))
{
lvProject.SelectedIndex = i;
break;
}
}
Hope it helps!
How do you bind ListView Items?
If you are using database level paging (stored procedure, query) - you should do search in the same way - using database query/stored procedure by passing a search criteria.
If you are bind ListView Items to a collection of items which are provided by a business/data layer - you have to create search method on layer which provides items so this method will be able to loop through the items.
You should set the SelectedIndex property to i
for (int i = 0; i < lvProject.Items.Count; i++)
{
if (((Label)lvProject.Items[i].FindControl("Project_IDLabel")).Text == project.ToString())
{
lvProject.SelectedIndex = i;
break;
}
}

Find selected WPF Listbox entries

I've been trying iterate through the selected items of a listbox in WPF, with the following code;
try
{
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
ListItem li = (ListItem)mylistbox.SelectedItems[i];
string listitemcontents_str = li.ToString();
}
}
catch(Exception e)
{
// Error appears here
string error = e.ToString();
}
However I receive an invalid cast exception;
System.InvalidCastException: Unable to cast object of type 'mylist' to type 'System.Windows.Documents.ListItem'.
Is there a way around this?
I prefer to do it using data binding:
Sync SelectedItems in a muliselect listbox with a collection in ViewModel
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
List**Box**Item li = (List**Box**Item)mylistbox.SelectedItems[i];
string listitemcontents_str = li.ToString();
}
This should work:
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
var li = mylistbox.SelectedItems[i];
string listitemcontents_str = li.ToString();
}
A way I found was to assign the listbox onto an object then cast this onto a DataRowView. Seems to work and I can get access to the fields inside, by their respective column names.
object selected = mylistbox.SelectedItem;
DataRow row = ((DataRowView)selected).Row;
string thecontents = row["columnname"].ToString().TrimEnd();
You are confusing ListItem with ListBoxItem.
If you do nothing special, a ListBox will create ListBoxItem containers for the data you bind to it. ListItem is used inside FlowDocument and is basically a numbered or bulleted point in a document.
That said, data binding would be better. If you were using data binding, SelectedItems would not be a ListBoxItem but would be your actual data item that was bound. You can cast this to the appropriate type and use it.
The listbox adds it's items as a collection of objects, so it can't cast it to ListItem.
So for your purpose , you can do as following :
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
string listitemcontents_str = mylistbox.SelectedItems[i].ToString();
}
If you really want to use ListBoxItem , please add these items to your listbox e.g.
ListBoxItem li = new ListBoxItem();
li.Content = "Hello";
mylistbox.Items.Add(li);
then you can do what you want without Invalid cast exception:
for (int i = 0; i < mylistbox.SelectedItems.Count; i++)
{
ListBoxItem li = (ListBoxItem)mylistbox.SelectedItems[i];
string s = li.ToString();
}

Categories

Resources