update a list after deleting an item - c#

i have a form that when i add a item it stores it within a list and adds it to a checklistbox
i have a button that deletes the item from the checklist box, but how would i get it so that when i delete it from the checklistbox it also deletes it within the list its been stored in
here is the code for the delete button
private void btnDelete_Click(object sender, EventArgs e)
{
for (int i = clbSummary.CheckedIndices.Count - 1; i >= 0; --i)
{
clbSummary.Items.RemoveAt(clbSummary.CheckedIndices[i]);
}
}

Why don't you do remove the item from the list within the btnDelete_Click method.
For example:
private void btnDelete_Click(object sender, EventArgs e)
{
for (int i = clbSummary.CheckedIndices.Count - 1; i >= 0; --i)
{
object item = clbSummary.Items[clbSummary.CheckedIndices[i]];
myList = myList.Remove(item);
clbSummary.Items.RemoveAt(clbSummary.CheckedIndices[i]);
}
}
I'm not sure if you can use the [] operator on Items, but this is to give you a general idea.

Set the checklistbox DataSource property to the list where you are storing the items. When you make any changes to the list, your checklistbox will update.

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

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

How to select previous item in listbox?

I have a timer in every tick it adds an item to listbox (or tuple which has two double integer).
For example:
20.157
20.158
20.159
20.160
...
But I want to separate items to 2 listboxes which has original order and which has ignores first or the last item.
For instance:
Listbox1 Listbox2
20.157 -
20.158 20,157
20.159 20.158
20.160 20,159
... ...
So how can I seperate items in 2 listboxes as I showed you above?
here is my code;
private void timer1_Tick(object sender, EventArgs e)
{
myTuple2.Add(new Tuple<double,double>
(Convert.ToSingle(gPathBoylam),Convert.ToSingle(gPathEnlem)));
}
private void pictureBoxPath_Paint(object sender, PaintEventArgs e)
{
for (int i = 0; i < myTuple2.Count-1 ; i++)
{
listBox1.Items.Add(myTuple2[i].Item1);
listBox2.Items.Add(myTuple2[i-1].Item1);
}
}

Listbox deselect top item

I have a listbox and I want to deselect the first selected item in the list when the loop is run because it should process a list item after item. Currently I'm using this:
var list = new object[listBoxTracks.SelectedItems.Count];
for (int i = 1; i < listBoxTracks.SelectedItems.Count; i++)
list[i - 1] = listBoxTracks.SelectedItems[i];
listBoxTracks.SelectedItems.Clear();
foreach (var track in list)
listBoxTracks.SelectedItems.Add(track);
I think/know that this is probably very bad but I have no idea what other possibilities there are. I tried stuff with selectedIndex += 1 etc but that seems to crash it. If this has been answered before I'm sorry but I haven't found anything in my research :/
As far as I see, you can directly manipulate the SelectedItems. So you can also remove a single item from it, e.g.
listBoxTracks.SelectedItems.Remove(listBoxTracks.SelectedItems[0]);
private void checkedListBox1_SelectedValueChanged(object sender, EventArgs e)
{
checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
}
private void checkedListBox1_MouseDoubleClick(object sender, MouseEventArgs e)
{
checkedListBox1.SetItemChecked(checkedListBox1.SelectedIndex, true);
}
This Will Do It for Sure , wanted this for me as well...

How to populate (mark checked) a checkedListBox with a StringCollection

I have a checkedListBox with 10 Items in my Collection on my windows form. Using C# VS210.
I am looking for a simple way to mark as checked only 2 of the items from my checkedListBox by using values stored in the Settings.Settings file, (stored as System.Collections.Specialized.StringCollection). I have not been able to find this example out there, I know I am supposed to use the CheckedListBox.CheckedItems Property somehow, but haven't found an example.
private void frmUserConfig_Load(object sender, EventArgs e)
{
foreach (string item in Properties.Settings.Default.checkedListBoxSystem)
{
checkedListBoxSystem.SetItemCheckState(item, CheckState.Checked);
}
}
How about using an Extension method?
static class CheckedListBoxHelper
{
public static void SetChecked(this CheckedListBox list, string value)
{
for (int i = 0; i < list.Items.Count; i++)
{
if (list.Items[i].Equals(value))
{
list.SetItemChecked(i, true);
break;
}
}
}
}
And slightly change the logic in your load event, like this:
private void frmUserConfig_Load(object sender, EventArgs e)
{
foreach (string item in Properties.Settings.Default.checkedListBoxSystem)
{
checkedListBoxSystem.SetChecked(item);
}
}
The first parameter of SetItemCheckState takes an index (int). Try to get the index of the item you want to check, and then use SetItemCheckState with the index to check it.

Categories

Resources