Problems with selected indices in listview - c#

I have an arraylist which contain objects of my own class. I want to fetch the object from the array list which has the index = selectedindex of listview.
I tried this :
TrackInformation t=(TrackInformation) SongList[listView1.SelectedIndices[0]];
TrackInformation is my class and SongList is an ArrayList of type TrackInformation.
listview1 does not allow multiple indices selection so I want the first element of the SelectedIndices collection.
I am getting ArgumentOutOfRangeException and it says value of '0' is not valid for 'index'.

Put this line before your code -
if(listView1.SelectedIndices.Count > 0)
{
TrackInformation t=(TrackInformation) SongList[listView1.SelectedIndices[0]];
}

The ListView.SelectedIndexChanged event has a quirk that bombs your code. When you start your program, no item is selected. Click an item and SelectedIndexChanged fires, no problem. Now click another item and the event fires twice. First to let you know, unhelpfully, that the first item is unselected. Then again to tell you that the new item is selected. That first event is going to make you index an empty array, kaboom. RV1987's snippet prevents this.

The error is because listView1.SelectedIndices is empty, do you have a row selected?
you probable want to wrap in a test
ListView.SelectedIndexCollection selected=listView1.SelectedIndicies;
if (selected.Count==0) {
// code for no items selected
} else {
TrackInformation t=(TrackInformation) SongList[selected[0]];
// rest of code to deal with t
}

Related

Need help in a school programming internal

I have two lists called standards and credits. The standards list is added to a ComboBox. When I click an item in the ComboBox I want to be able to show an item in the credits list. For example I click first index in the ComboBox, I want to show item in the first item of the credits list. I have this code but it gives me an error I can't fix it. This is the error im getting:
System.ArgumentOutOfRangeException
It's from this line of code
lblCredits.Text = credits.ElementAt(standard.IndexOf(cboStandard1.Text))
-
private void cboStandard1_SelectedIndexChanged(object sender, EventArgs e)
{
if (cboStandard1.SelectedIndex + 1 > 0)
{
lblCredits.Text = credits.ElementAt(standard.IndexOf(cboStandard1.Text));
}
}
This is showing that my lists are the same length
private void standardlist()
{
standard.Add("91632");
standard.Add("91633");
standard.Add("91634");
standard.Add("91635");
cboStandard1.DataSource = standard;
((ComboBox)cboStandard1).SelectedIndex = -1;
credits.Add("4");
credits.Add("6");
credits.Add("4");
credits.Add("4");
}
Like I said, binding the ComboBox, i.e. setting its DataSource property, will select the first item by default, which will raise the SelectedIndexChanged event, which will execute your code. That all happens before you've populated the credits list, which is why it contains no items. There are two things you can do, and you may choose to do both:
Populate the credits list before setting the DataSource of the ComboBox.
Handle the SelectionChangeCommitted event instead of SelectedIndexChanged.
The SelectionChangeCommitted event is raised only when the user selects an item via the UI, so it will not be raised when you bind the data and then reset the SelectedIndex, while SelectedIndexChanged will be raised twice. Even if you do implement option 1, you'll still have an issue on the second SelectedIndexChanged event because you'll be passing -1 to ElementAt, so you'll get an ArgumentOutOfRangeException thrown.

DropDownList Showing First Item Empty

Every time this Dropdown is showing first Item Blank
ComboBox cb;
List<string> namesCollection=new List<string>();
namesCollection.Add("---- Select ----");
namesCollection.Add("ABC1");
namesCollection.Add("ABC2");
namesCollection.Add("ABC3");
namesCollection.Add("ABC4");
foreach(string pname in namesCollection)
cb.Items.Add(pname);
Does anyone have solution for this ?
You appear to be defining the ComboBox right there in your code, so I'll assume it's actually displayed somewhere in your form / window.
It's normal for the ComboBox to display a blank line initially.
Specify the item you want to display, immediately after populating the ComboBox with data:
cb.SelectedIndex = 0;
You probably have a line feed in your items collection. Hard to see. Adding a cb.Items.Clear() before populating is probably a good idea anyway and will get rid of the problem, if you can't locate it.

Listbox multiple selection always selected all

I have one problem with listbox.
I use a listbox and the count is added when selecting the listbox items. But I have two items in the listbox that are always selected and the count is always 2.
What do I do to select a single or mutiple selection?
Two items always selected because of below two reasons:
1) They are selected in the inline code - selected = "true"
2) They are getting selected in the PageLoad method of codebehind and you are calling without Not IspostBack.
Please check.
One fact is you've set Mutliple selection mode.
another fact, is when you insert an item it is selected, if add another both are selected.
So after you add an item set
ListBox1.SelectedIndex = -1;
Otherwise, check suggestions given by Saurabh
Set ListSelectionMode to Multiple and then iterate through the listbox items
foreach (ListItem item in ListBox1.Items)
{
if(item.Selected)
{
count++;
}
}

Double-Clicking Item in ListView

So I added a list view, and I am displaying 3 columns of strings in each. I also have the full row select on. I want to be able to double click on one of the rows, and have it return the string in the 3rd column. I've tried to look everywhere for a solution to this, but so far nothing comes up.
My code so far is:
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
MessageBox.Show(songList.SelectedItems[2].ToString());
}
Yet it returns an error saying "InvalidArgument=Value of '2' is not valid for 'index'.
Parameter name: index"
You could try:
if (songList.SelectedItems.Count > 0)
{
ListViewItem item = songList.SelectedItems[0];
string s_you_want = item.SubItems[1].Text;
}
Taken a ListViewItem, you can take columns values using SubItems[] property.
I think that you hould bound not your listView to doubleClick event, but listViewItem. sender will have DataContext, from which you can get your third column.
How do you fill the ListView? Wihtout knowing this, it's difficult to help. May be you could try this:
Set a breakpoint in this line:
MessageBox.Show(songList.SelectedItems[2].ToString());
As soon as the debugger hits the breakpoint you could select songList and hit Shift-F9.
Now you can explore the songList and check yourself how to get the string of the third column.
SelectedItems returns a SelectedListViewItemCollection and with the indexer you are accessing elements in this collection, i.e. ListViewItems, not the columns. this means that if you have a single row selected the collection contains only one item, and trying to access the third one gives you the error.
Try (edit according to Marco's comment):
songList.SelectedItems[0].SubItems[1].Text

Listbox item stay focused after selection

I don't know if the title express what I want. I have a ListBox in WPF where I generate many elements. When I click on a element while still generating I want my selected item to not move down the list, so I cannot see it anymore, I want to stay in the exact position where I click on it.
If this is possible, can someone point some ideas on how to do it in C#?
Thanks.
Assuming that this is even a good idea and that you are using winforms
Step 1:
Determine the index of the selected item in the source.
Step 2:
When your adding items to the ListBox split the ListBox at the index where the item previously was insert the item at that point, then add on the remainder of the items, while making sure that you've removed the item if it is now elsewhere in the list.
Code:
//Let's assume that you know how to get the position of the item when it is clicked and save the
//item to a variable called OriginalItem
public void PutTheItemInTheSameSpot()
{
var listboxitems = (List<Integer>)YourListBox.DataSource;
var originalClikedItem = OriginalItem;
var topPart = new List<Integer>();
for (i = 0; i < itemPosition; i++)
{
topPart.Add(listboxItems[i]);
}
topPart.Add(originalClickedItem);
var bottomPart = listboxitems.Remove(toppart);
YourListBox.DataSource = toppart.AddRange(bottomPart);
}
Saw your edit about it being WPF
The could should work in idea.
Just a thought: you could try having your view respond to an event whenever an item is added to your ListBox. In the event handler, you could force the selected item to scroll into view presumably keeping it in the current "viewable" position:
listBox.ScrollIntoView(listBox.SelectedItem);
I've never tried this before so it may or may not produce the desired affect?

Categories

Resources