What I have going on is i am using
string proj = listView2.SelectedItems[0].ToString();
to capture the item of my selected listview item, this works fine the first around, when i click on another listview item it throw the exception of
InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index
Any thoughts?
private void listView2_SelectedIndexChanged(object sender, EventArgs e)
{
string proj = listView2.SelectedItems[0].ToString();
}
working:
string proj ="";
ListView.SelectedListViewItemCollection lv2si =
this.listView2.SelectedItems;
foreach (ListViewItem item in lv2si)
{
proj = item.ToString();
}
What if no item is selected in listview ? The collection will contain zero items and it will throw this exception.
Instead, obtain ListViewItemCollection and use foreach to iterate over it. As described in MSDN example:
ListView.SelectedListViewItemCollection breakfast =
this.ListView1.SelectedItems;
double price = 0.0;
foreach ( ListViewItem item in breakfast )
{
price += Double.Parse(item.SubItems[1].Text);
}
http://msdn.microsoft.com/en-us/library/system.windows.forms.listview.selecteditems.aspx
You should test that the index value is valid before you access it.
private void listView2_SelectedIndexChanged(object sender, EventArgs e)
{
string proj;
if (listView2.SelectedItems.Count > 0)
proj = listView2.SelectedItems[0].ToString();
else
proj = string.Empty;
}
The SelectedIndexChanged event is raised whenever the Selected property of a ListViewItem changes. This means the event is raised twice: once when the first item is deselected, and a second time when the item you clicked on is selected. Since you are not checking whether SelectedItems has any items, you get the exception the first time the event is raised.
As #Jeffrey L Whitledge shows in his answer, you can use SelectedItems.Count to determine whether any items are selected.
Related
I have a list view with the multiselect property set to false. When the user clicks on it, I take the NAME property of the list view item and convert it to a decimal then feed that to a method that loads the correct record.
The code below works perfectly when I select one item regardless of how many items are in the list and regardless of which item I select.
private void ListInstruments_SelectedIndexChanged(object sender, EventArgs e)
{
ListViewItem selection = listInstruments.SelectedItems[0];
if (selection != null)
{
string strSelection = selection.Name;
SelectedInstrumentID = Convert.ToDecimal(strSelection);
LoadSelectedInstrument();
}
}
When I make a second selection (not multi-select, but a different selection from the listbox) I get an error referencing listInstruments.SelectedItems[0].
System.ArgumentOutOfRangeException Message=InvalidArgument=Value of
'0' is not valid for 'index'. Parameter name: index
Source=System.Windows.Forms
Any help would be appreciated.
It's possible, that no items are selected, and thus list.SelectedItems is empty; you are tring to get 0th item from the empty collection and thus have the exception thrown. The quick patch is
// instead of original
// ListViewItem selection = listInstruments.SelectedItems[0];
ListViewItem selection = list.SelectedItems.Count > 0
? listInstruments.SelectedItems[0] // the collection has at least one item
: null; // if the collection is empty
Or we can check if we have a selection and return when there's none
private void ListInstruments_SelectedIndexChanged(object sender, EventArgs e)
{
if (list.SelectedItems.Count <= 0)
return;
listViewItem selection = listInstruments.SelectedItems[0];
string strSelection = selection.Name;
SelectedInstrumentID = Convert.ToDecimal(strSelection);
LoadSelectedInstrument();
}
I have a long list selector that is populated dynamically meaning the user adds items there.
This is the way items are added.
source.Add(new ShoppingList(Item1.Text));
Item1 is a textbox via which user adds stuff to the list.
I have a long list selector. Let's call it LLS. I want that when a certain itam is tapped, the text within the item is copied and pasted into a textblock.
So far I have tried the following:
string item = LLS.SelectedItems.ToString(); TextBlock.Text = item;
How can this be achieved?
Thank You for your attention and answers.
ShoppingList sitem = LLS.SelectedItem as ShoppingList;
string item = string.empty;
if ( sitem != null )
{
item = sitem. (property where you text is stored)
}
You have to subscribe to SelectionChanged Event:
private void LLS_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (LLS.SelectedItem != null)
{
ShoppingList item = LLS.SelectedItem as ShoppingList;
TextBlock.Text = item.yourProperty;
}
}
BTW - there are already similar questions: one, two and probably more.
I'm having some problem to get the index of the selected row in a listview. I wonder why this code isn't working? I get a red line below the SelectedIndex
private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
{
int index = lvRegAnimals.SelectedIndex;
string specialData = motelManager.GetInfoFromList(index);
UppdateSpecialData(specialData);
}
Help is preciated. Thanks!
EDIT:
For some strange reason I get two messages when I click on one of the lines in the listView!? First I get the previous number and then the number for the last clicked line. What could be wrong?
private void lvRegAnimals_SelectedIndexChanged(object sender, EventArgs e)
{
int index = lvRegAnimals.FocusedItem.Index;
MessageBox.Show(Convert.ToString(index));
}
It's working now when I added a check like this:
if(lvRegAnimals.SelectedIndices.Count > 0)
Because ListView doesn't contain any SelectedIndex, instead there is a property of SelectedIndices.
var indices = lvRegAnimals.SelectedIndices;
//indices[0] you can use that to access the first selected index
ListView.SelectedIndices
When the MultiSelect property is set to true, this property returns a
collection containing the indexes of all items that are selected in
the ListView. For a single-selection ListView, this property returns a
collection containing a single element containing the index of the
only selected item in the ListView.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
// Acquire SelectedItems reference.
var selectedItems = listView1.SelectedItems;
if (selectedItems.Count > 0)
{
// Display text of first item selected.
this.Text = selectedItems[0].Text;
}
else
{
// Display default string.
this.Text = "Empty";
}
}
Try :
listView1.FocusedItem.Index
This give you the index of the selected row.
There is another thread like this one, but here it goes again.
It can return NULL. Also the SelectedIndexChanged event can be FIRED TWICE. And the first time, there nothing selected yet.
So the only safe way to find it is like this:
private void lv1_SelectedIndexChanged(object sender, EventArgs e)
{
if (lv1.FocusedItem == null) return;
int p = lv1.FocusedItem.Index;
... now int p has the correct value...
The ListView is a darn hassle to work with sometimes.
A simple solution i've used is a for loop that checks for the
selected Item.
I've put my solution in the "When index change trigger" within the ListView.
Example:
int sel_item = 0; //an int to store the selected item index.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < listView1.Items.Count; i++)
{
if (listView1.Items[i].Selected == true)
{
sel_item = i;
}
}
}
This would ofcourse only work correctly with the "Multiselection" option set as false.
I need to pass a checkeditem of a checklistbox while firing an event from a dynamic checklistbox. The code snippet is provided below with comments...
I'm facing an issue with the same piece of code. On mouse double click event its throwing an exception saying IndexoutofRange. Its working fine with the index value 0.Please help 2 solve me both.
private void clbTables_MouseDoubleClick(object sender, MouseEventArgs e)
{
int indexofselectedtable;
indexofselectedtable = Convert.ToInt32(clbTables.SelectedIndex);
if (clbTables.CheckedItems.Count != 0)
{
Metadata metadataobj = new Metadata(dbProperties);
DBList = metadataobj.GetColumns(clbTables.CheckedItems[indexofselectedtable].ToString()); // This throws an error on checking an item of index>0.
for (int j = 0; j < DBList.Count; j++)
{
chklistcolumns.Name = "chklist" + j++;
chklistcolumns.Items.Add(DBList.ElementAt(j));
}
this.Controls.Add(chklistcolumns);
chklistcolumns.ItemCheck += new ItemCheckEventHandler(OnCheckListBoxItemCheck);
}
}
private void OnCheckListBoxItemCheck(object sender, ItemCheckEventArgs args) //need to pass the tablename which can be got from the object clbTables
{
Columns columnobj = new Columns();
columnobj.ColumnName = this.Text;
columnobj.Id = this.Name;
columnobj.TableName= // need to get the tablename from the object clbtables
}
I think I see what the issue here is, you are trying to match the selected index of your CheckedListBox with an index in the CheckedItems collection, but it doesn't work that way.
Consider this: you have 10 items in your CheckedListBox, and three of them are checked. That gives you .Items[10] and .CheckedItems[3]. If then you double click on the 7th item in the CheckedListBox, your SelectedIndex will be 6, but there will only be three items in the CheckedItems collection. So when you try to read clbTables.CheckedItems[6] you are going to be outside of the range of that collection.
clbTables.CheckedItems is another collection. You can't use clbTables.SelectedIndex in it.
Why not just to use SelectedValue property?
I have ListView which shows images from an ImageList. Now wanted to get index of all checked images in ListView.
List<int> list = new List<int>(); // in list index of all checked images on clicking button should be saved.
private void button2_Click(object sender, EventArgs e)
{
ListView.CheckedListViewItemCollection checkedItems = lstview1.CheckedItems;
foreach (ListViewItem item in checkedItems)
{
list.add[// How can i get index of checked item ];
}
}
ListView already has the CheckedIndices property. You probably ought to use it directly, but you can get a List<> out of it with a Linq one-liner:
var list = listView1.CheckedIndices.Cast<int>().ToList();
Well, I'm not sure I understand your question completely, but you can get the index of a ListViewItem with item.Index.
ListView.CheckedListViewItemCollection checkedItems = lstview1.CheckedItems;
foreach (ListViewItem item in checkedItems)
{
// This will fill the list with ListViewItems that are checked
list.add(listview1.Items[item.Index]);
}