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]);
}
}
}
Related
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++;
}
}
I am having trouble with removing an item from a list in c#. My current code is below:
for (int i = current.Count - 1; i >= 0; i--)
{
foreach (ListItem li in sp_list.Items)
{
if (li.Text == current[i].uname)
{
current.RemoveAt(i);
}
}
}
The aim of the code is to compare the existing items in a list box with newly added items so I know which items have just been added. So currently I am getting the current list box items from the database (they are stored here, it is a databound list box), entering these into a list and for each of the list items, comparing them with the items in a list box and if they match, remove the item from the list.
Therefore, in the end, if I add two new entries, the list should only be storing the two newly added values.
The code does not work as the first item is removed fine, but then, the value of i is greater than current.count - and therefore I get an out of range exception!
Could someone help me with this issue? Apologies about the confusing question, it's hard to explain! Thanks
You can do it with Linq. Not sure if casting to ListItem needed (you can remove it)
current.RemoveAll(x => sp_list.Items.Cast<ListItem>()
.Any(li => li.Text == x.uname));
Once you've found the matching value, and removed it from the list, you want to break out of the inner loop to check the next item.
if (li.Text == current[i].uname)
{
current.RemoveAt(i);
break;
}
Your nesting is wrong, I think you wanted,
foreach (ListItem li in sp_list.Items)
{
for (int i = current.Count - 1; i >= 0; i--)
{
if (li.Text == current[i].uname)
{
current.RemoveAt(i);
}
}
}
alternatively, use linq,
// For lookup performance.
var items = new HashSet(sp_list.Items.Select(i => i.text));
current = current.Where(c => !items.Contains(c.uname)).ToList();
How about this:
foreach (ListItem li in sp_list.Items) {
if (current.Contains(li.Text)) {
current.Remove(li.Text);
}
}
Put a break statement after the RemoveAt so you don't remove that item again.
you can travel the list in reverse order and remove items using RemoveAt(i).
also for efficiency purposes you may want to put the ListItem texts in a Set so you can don't have to loop though the sp_list.Items for each of your current items.
I am new to c#. In my project I have two controls ListBox and ListView
ListBox --> lbxEmpName
ListView --> lvEmpDetails
I tried the below code:
if (lvEmpDetails.Items.Count > 0)
{
for (int intCount = 0; intCount < lbxEmpName.Items.Count; intCount++)
{
for (int intSubCount = 0; intSubCount < lvEmpDetails.Items.Count; intSubCount++)
{
if (lvEmpDetails.Items[intSubCount].Equals(lbxEmpName.Items[intCount]))
{
lbxEmpName.Items.Remove(lbxEmpName.Items[intCount]);
}
}
}
}
If I run the above code, there are no matches between ListView Items and ListBox Items (Infact there must be some matches). When I debug my code, I saw the below thing: It is saying SelectedItem whereas I am giving here Items (Thats why my program is not matching items)
why it is showing SelectedItem = "" instead of Items ?
Am I doing something wrong in my code? Please suggest.
ListView's Items contains objects of type ListViewItem. So there is no use in comparing those with objects in ListBox's Items.
If you want to compare their text, you must write something like this:
if (lvEmpDetails.Items[intSubCount].Text == (string)lbxEmpName.Items[intCount])
{
// Do something here
}
Please note that a ListViewItem can have multiple sub-items and its Text property returns the first column of its data.
Compare the string values that you want to compare not the object themselves.
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;
}
}
I've just started to use ListView in C#.net.
I got to know how to add items and subitems. Going through the listview I wanted to fetch all the data from a whole column with multiple rows.
I want to know how to do this.
I found this code to list a specific selected data from a row:
ListView.SelectedIndexCollection sel = listView1.SelectedIndices;
if (sel.Count == 1)
{
ListViewItem selItem = listView1.Items[sel[0]];
MessageBox.Show(selItem.SubItems[2].Text);
}
That was helpful but i want to list all the items in a row, may be i want to add all the column items in array?
private string[] GetListViewItemColumns(ListViewItem item) {
var columns = new string[item.SubItems.Count];
for (int column = 0; column < columns.Length; column++) {
columns[column] = item.SubItems[column].Text;
}
return columns;
}
I would recommend some caution against doing this. A ListView is really meant to display information, it is not a great collection class. Getting the data out of it is slow and crummy, it can only store strings. Keep the data in your program in its original form, maybe a List<Foo>. Now it is simple and fast.
foreach (ListViewItem item in listView1.Items) {
// Do something with item
}
you could do this by
foreach(ListViewItem item in listView1.Items)
{
foreach(var subtem in item.SubItems)
{
// Do what ever you want to do with the items.
}
}