Error when selecting second item from ListView C# - c#

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();
}

Related

How to select item from listview in selectedindexchanged event?

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
img1 = Image.FromFile(listView1.SelectedItems[0].Text);
pictureBox1.Image = img1;
}
I have 10 items in the listView.
If I'm using it like it is now with SelectedItems[0].Text, when I select any item, the first time it's working fine, but then when I'm selecting another item, it's throwing this error :
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '0' is not valid for 'index'.
Parameter name: index'
When the event is raised, the details of the item are passed into the event, via 'e'. The type of e will be a ListViewItem, therefore you can use e.Item.Text to access the text of the selected item.
The reason you may be seeing the exception is because I suspect as the selected index changes, it may be unselecting the selected item before it selects the new one, therefore, there isn't an item at Index 0 in this case. You could get around this by wrapping your existing code in an "IF" check like so:
if (listView1.SelectedItems[0] is not null)
{
//DO PROCESSING HERE
}

findstring method in listbox not working ? c#

trying to get a specific item in a list box which will then load new web page
getting error saying listbox doesnt have 'findString' method?
Am i possibly missing a using ?
protected void lstVideos_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the currently selected item in the ListBox.
string curItem = lstVideos.SelectedItem.ToString();
// Find the string in lstVideos.
int index = lstVideos.FindString(curItem);
// If the item was not found in lstVideos display a message box, otherwise select it in lstVideos.
if (index == 1)
{
}
The code you are trying is for windows form ListBox and not for asp.net ListBox control. You can simply use SelectedIndex property to get the selected index:-
int index = lstVideos.SelectedIndex;

Cannot perform runtime binding on a null reference when using type dynamic

I have a listview and this listview will be updated when a message is coming in.
The code below is about how I get the selected row's value.
private void CallTabLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string callDetailValue = "";
dynamic selectedCallDetail;
//When a row of call detail is selected, return the selected row's value only
if (LineBtn1.IsChecked == true)
{
selectedCallDetail = CallTabLv1.SelectedItem;
callDetailValue = selectedCallDetail.Value;
}
if (LineBtn2.IsChecked == true)
{
selectedCallDetail = CallTabLv2.SelectedItem;
callDetailValue = selectedCallDetail.Value;
}
if (string.IsNullOrEmpty(callDetailValue))
callDetailValue = string.Empty;
Clipboard.Clear();
Clipboard.SetText(callDetailValue);
}
It worked fine for first coming message and I could get the selected row's value. The problem is when second message came in, my application stopped and returned "Cannot perform runtime binding on a null reference".
By the way, to return single selected row' value, which one should be used: CallTabLv1.SelectedItem or CallTabLv1.SelectedItems[0]? As I tried, if the latter is used, it will return "ArgumentOutOfRange Exception" when second message is coming in.
Please help.
Update:
When the message is coming in, I update the listview by clearing the whole listview and then print it line by line. I'm not sure if it is caused by the way I update the listview.
So this is probably happening because you are clearing the collection in which you have now changed the selected item. Since the item can be null at that time the dynamic object will be unable to access the property "Value"
You are checking if a checkbox is checked which is not necessarily a condition of if the selected item will exist. I would suggest your code be updated as such.
private void CallTabLv_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string callDetailValue = "";
dynamic selectedCallDetail;
//When a row of call detail is selected, return the selected row's value only
if (LineBtn1.IsChecked == true)
{
selectedCallDetail = CallTabLv1.SelectedItem;
}
if (LineBtn2.IsChecked == true)
{
selectedCallDetail = CallTabLv2.SelectedItem;
}
// I think the 'invalid' casting is happening with the "selectedCallDetail.Value" as when you clear a listbox it is no longer selected.
callDetailValue = (selectedCallDetail != null) ? selectedCallDetail.Value : string.Empty;
Clipboard.Clear();
Clipboard.SetText(callDetailValue);
}
You should be using the SelectedItem as the SelectedItems collection may be null or empty, If you only ever want one result this is usually the best. also make sure your ListBox only allows for a single item to be selected so that the user cannot crash your code by selecting multiple items using SHIFT or CTRL click

Select index from listview

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.

listview to string exception thrown

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.

Categories