I have 2 Listboxes , each are on different tab page
listBox1 with items A,B,C and listBox2 with exactly same items A,B,C
When I select Item A from listBox1, I want Item A from listBox2 selected aswell and vice versa
I use this code :
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string item = listBox1.SelectedItem.ToString();
int index = listBox2_Fichiers.FindString(item);
listBox2.SetSelected(index, true);
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string item = listBox2.SelectedItem.ToString();
int index = listBox1_Fichiers.FindString(item);
listBox1.SetSelected(index, true);
}
It works only in one way, from 1 to 2 or from 2 to 1 , but when I try to activate both I get this exception: System.StackOverflowException
What am I missing ?
It is because everytime you call SetSelected, SelectedIndexChanged can be called.
This creates an infinite calling of listBox1.SetSelected > listBox1_SelectedIndexChanged > listBox2.SetSelected > listBox2_SelectedIndexChanged > listBox1.SetSelected > ....
Eventually, system stops you by throwing a StackOverflowException.
private bool mirroring = false;
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (mirroring) return;
mirroring = true;
string item = listBox1.SelectedItem.ToString();
int index = listBox2_Fichiers.FindString(item);
listBox2.SetSelected(index, true);
mirroring = false;
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
if (mirroring) return;
mirroring = true;
string item = listBox2.SelectedItem.ToString();
int index = listBox1_Fichiers.FindString(item);
listBox1.SetSelected(index, true);
mirroring = false;
}
It is your responsibility to break the call chain. Simplest way is using a boolean switch.
System.StackOverflowException
exception occurs when you are trying to create a loop of operation. You are changing list1 from list2's listBox2_SelectedIndexChanged event so it changes list1's index which fire list1's listBox1_SelectedIndexChanged event which again fire list2's same as before. So this thing creating a loop of selected index change event and System.StackOverflowException exception thrown. You have to change this event handling to prevent this
Related
I am working on a simple application that to add/delete string/s into an array and show that in ListBox.
My code shows only the latest value that was typed into the textBox and
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
List<string> ls = new List<string>();
ls.Add(add);
String[] terms = ls.ToArray();
List.Items.Clear();
foreach (var item in terms)
{
List.Items.Add(item);
}
}
private void Delete_Click(object sender, EventArgs e)
{
}
This code makes no sense. You are adding one single item to a list, then convert it to an array (still containg one item) and finally loop through this array, which of course adds one item to the previously cleared listbox. Therefore your listbox will always contain one single item. Why not simply add the item directly?
private void Add_Click(object sender, EventArgs e)
{
List.Items.Add(textBox1.Text);
}
private void Delete_Click(object sender, EventArgs e)
{
List.Items.Clear();
}
Also clear the listbox in Delete_Click instead of Add_Click.
If you prefer to keep the items in a separate collection, use a List<string>, and assign it to the DataSource property of the listbox.
Whenever you want the listbox to be updated, assign it null, then re-assign the list.
private List<string> ls = new List<string>();
private void Add_Click(object sender, EventArgs e)
{
string add = textBox1.Text;
// Avoid adding same item twice
if (!ls.Contains(add)) {
ls.Add(add);
RefreshListBox();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Delete the selected items.
// Delete in reverse order, otherwise the indices of not yet deleted items will change
// and not reflect the indices returned by SelectedIndices collection anymore.
for (int i = List.SelectedIndices.Count - 1; i >= 0; i--) {
ls.RemoveAt(List.SelectedIndices[i]);
}
RefreshListBox();
}
private void RefreshListBox()
{
List.DataSource = null;
List.DataSource = ls;
}
The problem with code is quite simple. Instead of adding new item to list your code creates new list with one added item only. I am trying to interpret functions of program and they seem to be:
Enter new text into top level text box.
If Add button is clicked your item goes on top of the list (if it's bottom see end of my answer).
If item(s) is selected in list and Delete is clicked selected item(s) is/are deleted.
To achieve this you should first insert text on top of the list by using Add_Click code, than delete selected items using Delete_Click code. There is additional code to guard against inserting empty or white space only strings plus trimming of leading and trailing white space.
private void Add_Click(object sender, EventArgs e)
{
// Since you do not want to add empty or null
// strings check for it and skip adding if check fails
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text)
{
// Good habit is to remove trailing and leading
// white space what Trim() method does
List.Items.Insert(0, textBox1.Text.Trim());
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Get all selected items indices first
var selectedIndices = List.SelectedIndices;
// Remove every selected item using it's index
foreach(int i in selectedIndices)
List.Items.RemoveAt(i);
}
To complete adding and deleting logic I would add Delete All button which would just call List.Items.Clear(). If you prefer to add text at the end just use Add method form #Olivier Jacot-Descombes answer.
You can use in C#:
private void Delete_Click(object sender, EventArgs e)
{
if(myList.Contains(textbox1.value))//if your list containt the delete value
{
myList.Remove(textbox1.value); //delete this value
}
else
{
//the list not containt this value
}
}
and you can use the same method for validate if a value exist when try to add
private void AddItem()
{
if (!String.IsNullEmptyOrWhiteSpace(textBox1.Text))
{
var newItem = textBox1.Text.Trim();
if (!List.Items.Contains(newItem))
{
List.Items.Add(newItem);
// Alternative if you want the item at the top of the list instead of the bottom
//List.Items.Insert(0, newItem);
//Prepare to enter another item
textBox1.Text = String.Empty;
textBox1.Focus();
}
}
}
private void Add_Click(object sender, EventArgs e)
{
AddItem();
}
Private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
AddItem();
}
}
private void Delete_Click(object sender, EventArgs e)
{
// Remove every selected item using it's index
foreach(var item in List.SelectedItems)
{
List.Items.Remove(item);
}
}
I need to implement a ComboBox, which acts as follows:
When Click on the ComboBox, the client calling API method and updates the combobox items with the response.
My problem is, when I have 0 results - I want the ComboBox not to open (It has 0 items).
Is there a way to do that?
This is my current code:L
private void Combo_DropDown(object sender, EventArgs e)
{
// Private method which addes items to the combo, and returns false if no itmes were added
if (!AddItemsToComboBox())
{
// This is not working
Combo.DroppedDown = false;
}
}
You can make the DropDownHeight as small as possible (1). For example:
int iniHeight;
private void Form1_Load(object sender, EventArgs e)
{
iniHeight = Combo.DropDownHeight;
}
private void Combo_DropDown(object sender, EventArgs e)
{
Combo.DropDownHeight = (AddItemsToComboBox() ? iniHeight : 1);
}
I would like remove item just before because its shows me twice the same item when I click on, but here, item number -1 doesn't exists
And I don't know why.
How I can resolve this ?
Thank you.
private void DEXTarget_CheckedChanged(object sender, EventArgs e)
{
Logs("DEX(TMAPI) Target Checked");
listView1.Items.RemoveAt(-1);
PS3.ChangeAPI(SelectAPI.TargetManager);
Var.API = true;
}
private void CEXTarget_CheckedChanged(object sender, EventArgs e)
{
Logs("CEX(CCAPI) Target Checked");
PS3.ChangeAPI(SelectAPI.ControlConsole);
Var.API = false;
}
Log:
private void Logs(string text)
{
Var.lst = this.listView1.Items.Add(DateTime.Now.ToString("dd/MM/yy HH:mm"));
Var.lst.SubItems.Add(text);
}
ListView Items Index start from 0 and ends with Count-1.
I think you are looking for removing the last Item from the ListView
Try This:
listView1.Items.RemoveAt(listView1.Items.Count - 1);
I have this event code of the listBox:
I tried ot do it this way and it's almost working good.
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
if (recentItems.Contains(listBox1.SelectedItem))
{
itemExist = true;
item = listBox1.SelectedItem.ToString();
this.f1.PlayLightnings();
f1.pdftoolsmenu();
}
else
{
itemExist = false;
item = listBox1.SelectedItem.ToString();
recentItems.Add(listBox1.SelectedItem.ToString());
this.f1.PlayLightnings();
f1.pdftoolsmenu();
}
}
Im using a new bool variable itemExist and check and if the List recentItems wich is don't contain the selectedItem add it.
And if it does exist set the flag to true.
Then in the other code in Form1 im doing:
if (Lightnings_Extractor.Lightnings_Mode.itemExist == true)
{
if (!pdf1.Lightnings.Contains(Lightnings_Extractor.Lightnings_Mode.item))
{
pdf1.Lightnings.Add(Lightnings_Extractor.Lightnings_Mode.item);
}
}
So it's working as i wanted but the problem is that each new item i select in the listBox click on it i have to click on it twice since first time it's not in the recentItems and only on the second click it does in the recentItems and only on the second click it's changing the flag to true.
So how can i solve this problem in the SelectedIndexChanged event ?
I saw now i don't need the code part in Form1 only this code:
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
item = listBox1.SelectedItem.ToString();
this.f1.PlayLightnings();
f1.pdftoolsmenu();
if (item != null && !pdf1.Lightnings.Contains(item.ToString()))
{
pdf1.Lightnings.Add(item.ToString());
}
}
I want to create a if statement that recognizes which string has been removed from a specific list box. I thought i could do an if statement similar to the one below and get it to work but it tells me it has invalid arguements - if anyone can guide me it would appreciated
private void button2_Click(object sender, EventArgs e)
{
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
if(listBox2.Items.RemoveAt(listBox2.SelectedItems.ToString().Equals("Test")))
{
picturebox.Image = null;
}
}
You need to check the SelectedItem before removing it:
private void button2_Click(object sender, EventArgs e)
{
if (listBox2.SelectedIndex != -1)
{
if (listBox2.SelectedItem.ToString().Equals("Test")))
picturebox.Image = null;
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
}
}
I’ve also added a check to ensure that an item is actually selected (since you would get errors otherwise).
Your issue is that you are calling ListBox.Items.RemoveAt(int index) and passing in a boolean value: listBox2.SelectedItems.ToString().Equals("Test")).
In addition, you're removing the item first, and then calling RemoveAt again, which will actually remove a different item (whatever is now at that index), or throw an exception if you've gone outside of the bounds of your ListBox collection.
You should first check if your selected item equals "Test", and then remove the item from your ListBox, like so:
private void button2_Click(object sender, EventArgs e)
{
// SelectedIndex returns -1 if nothing is selected
if(listBox2.SelectedIndex != -1)
{
if( listBox2.SelectedItem.ToString().Equals("Test") )
{
picturebox.Image = null;
}
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
}
}
You should do something like :
String deletedString = listBox2.Items.ElementAt(listBox2.SelectedIndex).ToString();
listBox2.Items.RemoveAt(listBox2.SelectedIndex);
if(listBox2.Items.RemoveAt(deletedString == "Test"))
{
picturebox.Image = null;
}
It might not compile (Check if Items has SelectedItem property).