C# ListView Remove Items - c#

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

Related

Searching and filtering out results from listbox in visual c#

I'm just learning how to code in c# and I'm trying to figure out a way to search and filter out results from a listbox that contains data. Right now I have a listbox and a search button, my listbox contains website history, and my search button finds the item in the list but I cannot find a way to filter out the other items so that only what I searched for in the textbox appears in the listbox. Right now my search button looks like this. Any ideas?
private void searchBtn_Click(object sender, EventArgs e)
{
listBoxHist.SelectedItems.Clear();
for (int i = 0; i < listBoxHist.Items.Count; i++)
{
if (listBoxHist.Items[i].ToString().Contains(textboxSearch.Text))
{
listBoxHist.SetSelected(i, true);
}
}
}
There is a well know 'trick' to remove items while iterating over a collection. You should iterate backwards (from the last item through the first) using the for...loop.
In this way, when you remove an item you don't affect the condition used to exit the loop and you are guaranteed that every item is evaluated.
private void searchBtn_Click(object sender, EventArgs e)
{
for (int i = listBoxHist.Items.Count - 1; i >= 0; i--)
{
if (listBoxHist.Items[i].ToString().Contains(textboxSearch.Text))
listBoxHist.SetSelected(i, true);
else
listBoxHist.Items.RemoveAt(i);
}
}
If you do this code while looping forward you will have problem to evaluate correctly every item. Suppose you remove an item when the index is 3. What happens to item in position 4? It slides down one position and now it occupies the position 3 and this happens to every other item after. Now your loop will increment the index to 4 and will start evaluating the item that was at position 5 before the call to RemoveAt. You have skipped the evaluation of an item.
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListBox1.Items.Add("B");
ListBox1.Items.Add("A");
ListBox1.Items.Add("P");
ListBox1.Items.Add("X");
ListBox1.Items.Add("F");
ListBox1.Items.Add("S");
ListBox1.Items.Add("Z");
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
String txt=txtsearch.Text;
if (ListBox1.Items.FindByText(txt)!= null)
{
// ListBox1.Items.FindByText(txt).Selected = true;
Response.Write("<script> alert('Item found.');</script>");
}
else
{
Response.Write("<script> alert('Item Not found.');</script>");
}
}
}

C# listview1 throws error after first selection

On my windows forms I have a listview control and I have an event handler of
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
the problme is after the first selection I am getting an error that says:
System.ArgumentOutOfRangeException: 'InvalidArgument=Value of '0' is not vaild for 'index'. Parameter name:index'
This is the full code:
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
MessageBox.Show(listView1.SelectedItems[0].Text);
}
This code allows for one selection to show up in a message box but the next selection comes up with the above error. Any ideas of how to fix this?
Your datasource or list's length is important in this case, without knowing that, you can check length inside event. The error says that; SelecteItems doesn't have any item inside. When you try to select 0 index of the list, it throws that the list doesn't have any item at index 0.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0){
MessageBox.Show(listView1.SelectedItems[0].Text);
}
}
Hope helps,
Check selected items count before to retrieve the selected item.
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0)
MessageBox.Show(listView1.SelectedItems[0].Text);
}
Yes that is the answer thank you!
private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{
if(listView1.SelectedItems.Count > 0)
MessageBox.Show(listView1.SelectedItems[0].Text);
}

Add and delete text to/from ListBox hosted in WinForm using C#

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

Mirror selection from 2 listbox

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

Edit Items in a ListBox

I am creating a program using WinForms so users can input info into textboxes on one form which then are saved into a Listbox on another form. I would like to be able to edit the items saved in the listbox by opening the original form on a button click. Really struggling with it as I can't think of the code and I can't seem to find a solution.
My Code:
private void btnAdd_Click(object sender, EventArgs e)
{
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.ShowDialog();
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
listBoxRooms.Items.Add(newRoomDisplayForm.value);
}
newRoomDisplayForm.Close();
}
private void btnRemove_Click(object sender, EventArgs e)
{
this.listBoxRooms.Items.RemoveAt(this.listBoxRooms.SelectedIndex);
}
private void btnEdit_Click(object sender, EventArgs e)
{
}
So i've got a Add and Remove button which work perfectly just need a solution to the edit button.
Thanks in advance
I'm guessing newRoomDisplayForm.value is a property or a public member inside the form. You just need to do something like this:
private void btnEdit_Click(object sender, EventArgs e)
{
if(listBoxRooms.SelectedIndex < 0) return;
var tmpValue = listBoxRooms.Items[listBoxRooms.SelectedIndex].ToString();
RoomDisplayForm newRoomDisplayForm = new RoomDisplayForm();
newRoomDisplayForm.value = tmpValue;
newRoomDisplayForm.ShowDialog();
//TODO: inside "newRoomDisplayForm" set the value to the textbox
// ie.: myValueTextBox.Text = this.value;
if(newRoomDisplayForm.DialogResult == DialogResult.OK)
{
// replace the selected item with the new value
listBoxRooms.Items[listBoxRooms.SelectedIndex] = newRoomDisplayForm.value;
}
}
Hope it helps!
You can simply remove the listitem in that specific position, create a new item and add it again. it's kind of replacement.

Categories

Resources