SelectedIndexChanged event to occur in button click - c#

I have a command that delete the selected item in listBox. How I will change the selection on the other item of listbox after executing the delete command?

under button command, write this, it will delete the selected item in listview.
listBox1.Items.Remove(listBox1.SelectedItem);

Actually what you are trying to say is not complete,but what i am getting is that you want to delete currently selected item in ListBox;you can do it this way;
int index=0; //Set its value corresponding to item you want to delete.
listBox1.Items.RemoveAt(index); //This will remove selected item.
Now if you want the next item to be selected as soon as this one's removed,add this;
if(index!=-1)
{
int nextindex=index+1; //Calculates the index of next item.
listBox1.SelectedIndex=nextindex; //Selects next item.
}

private void button1_Click(object sender, EventArgs e) {
int i = listBox1.SelectedIndex;
if(i > -1) {
listBox1.Items.RemoveAt(i);
if(listBox1.Items.Count > 0)
listBox1.SelectedIndex = i < listBox1.Items.Count ? i : listBox1.Items.Count - 1;
}
}

Related

Changing the SelectedIndex in a ListBox programmatically after removing an Item

I would like to remove items from a ListBox and set the selected index to the next item.
<ListBox x:Name="lstBox" KeyDown="lstBox_KeyDown">
<ListBoxItem>A</ListBoxItem>
<ListBoxItem>B</ListBoxItem>
<ListBoxItem>C</ListBoxItem>
<ListBoxItem>D</ListBoxItem>
<ListBoxItem>E</ListBoxItem>
</ListBox>
This code works as intended unless i use the arrow keys. If i delete "B" for instance the next selected item is "C". However using cursor down will select the first item "A" instead of "D".
private void lstBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Delete)
{
if (lstBox.SelectedIndex == -1)
return;
int currentIndex = lstBox.SelectedIndex;
int newIndex = lstBox.SelectedIndex;
//in case the last item was deleted
if (newIndex == lstBox.Items.Count - 1)
newIndex--;
lstBox.Items.RemoveAt(currentIndex);
lstBox.SelectedIndex = newIndex;
}
}
I have already tried to set the focus to the ListBox after setting the new index. But it doesn't help.
lstBox.SelectedIndex = newIndex;
lstBox.Focus();
How can i fix that?
This issue is due to the fact that when you are removing one item, ListBox loses the focus.
So in order to make your arrow keys work, you will also have to set the focus on Selected Item of the Listbox
<ListBox x:Name="lstBox" KeyDown="lstBox_KeyDown" SelectionChanged="LstBox_OnSelectionChanged">
<ListBoxItem>A</ListBoxItem>
<ListBoxItem>B</ListBoxItem>
<ListBoxItem>C</ListBoxItem>
<ListBoxItem>D</ListBoxItem>
<ListBoxItem>E</ListBoxItem>
</ListBox>
private void LstBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
var item = (ListBoxItem)lstBox.ItemContainerGenerator.ContainerFromItem(lstBox.SelectedItem);
if (item != null)
item.Focus();
}

How to clear listbox selection if I click empty field of listbox?

I have a simple Windows Form which contains a list box called lstVersenyzok. I have a lstVersenyzok_SelectedIndexChanged function. How can I clear the selection of the list box when I click the empty field of the list box? I tried, but it does not work if I check the condition lstVersenyzok.SelectedIndex == -1.
You can use MouseClick event and get the selected index by the IndexFromPoint method.
Check if the index is -1, then call the lstVersenyzok.ClearSelected() to clear the selection.
private void lstVersenyzok_MouseClick(object sender, MouseEventArgs e)
{
int index = this.lstVersenyzok.IndexFromPoint(e.Location);
if(index == -1)
{
lstVersenyzok.ClearSelected();
}
}
Hope this help !!

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.

on selecting an item in listbox disable a button

On selecting the firstitem in the list box my Up button should be disabled. similarly on selecting the Lastitem in the listbox Down button should be disabled. I can able to find which item is selected by using selected index
if (lstview.SelectedIndex >= 0)
{
var selectedItems = lstview.SelectedItems;
foreach (ClassName selectedItem in selectedItems)
{
lstview.Items.Remove(selectedItem);
break;
}
}
but how to disable the up and down button based on selecting first item or last item in the list box
Compare the selected index with 0, and the number of items in the list and set the Enabled property of your buttons based on the selected index.
private void lstView_SelectedIndexChanged(object sender, System.EventArgs e)
{
upButton.Enabled = lstView.SelectedIndex > 0;
downButton.Enabled = lstView.SelectedIndex < lstView.Items.Count - 1;
}

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