Search items in the listbox using index - c#

I am doing a project that uses listbox, I can add items, delete items, update items but I can't search,
this is my code for search
string search = Person.listperson[listBox1.SelectedIndex].lastname;
foreach (String s in search)
{
if (s.Equals(textBox6.Text))
{
//show searched items
MessageBox.Show("Success!");
}
}
can you help me with this?
thanks :)
I have here a code for search,
But it does not apply in the button, how can I apply this on the button?
private void textBox6_TextChanged(object sender, EventArgs e)
{
int index = listBox1.FindString(this.textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}

Try something like this, add a click event to your button and put your code in it. This works for me.
private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (index > -1)
{
listBox1.SelectedIndex = index;
}
}

Not sure what you're trying to do exactly, but here's some samples.
Also, start giving variables useful names. If you come back to this code in a month you'll have no idea what's going on there or what textBox6 is.
To find a string (textBox6) in the entire listperson collection:
var list = Person.listperson.Where(p => p.lastname.Contains(textBox6.Text));
To check if a specific item in listperson has a partial textBox6 value:
var search = Person.listperson[listBox1.SelectedIndex].lastname;
bool success = search.Contains(textBox6.Text);
Or if you'd rather compare the values:
bool success = (search == textBox6.Text);

you can foreach char in a string
string s = "Blippy you";
foreach (char item in s)
{
}
but anywho. try Text.RegularExpressions for string matching.

private void button1_Click(object sender, System.EventArgs e)
{
if (listBox1.FindString("Your String in Textbox 6") != -1)
{
MessageBox.Show("Success!");
}
}

Related

listView.Selectedindeces[0] Unhandled exception

I'm trying to locate the list item that a user selects in a ListView box, however, whenever I try to use listview.SelectedIndeces[0], I get an unhandled exception error stating "InvalidArgument=Value of '0' is not valid for "index"".
Here is the code:
private void TabPage3_Click(object sender, EventArgs e)
{
foreach (Child child in Children)
{
editChildListView.Items.Add(new ListViewItem(new string[] {child.name, child.dob.ToString("dd/MM/yy"), child.comment }));
}
if (editChildListView.Items.Count >= 0)
{
int selectedIndex = editChildListView.SelectedIndices[0];
editNameBox.Text = Children[selectedIndex].name;
}
}
ANSWER:
private void EditChildListView_SelectedIndexChanged(object sender, EventArgs e)
{
if (editChildListView.Items.Count >= 0)
{
int selectedIndex = editChildListView.SelectedIndices[0];
editNameBox.Text = Children[selectedIndex].name;
}
}
The method needed to be called from the listview_SelectedIndexChanged function rather than the tab3_Click function
If you do
int selectedIndex = editChildListView.SelectedIndices.FirstOrDefault();
Then you won't get an error if nothing is selected.
You probably just want to check something is selected.

Identify the Listbox Item through specific item

private void Form1_Load(object sender, EventArgs e){
for (int i = 0; i < listBox1.Items.Count; i++)
{
lst.Add(listBox1.Items[i].ToString());
}
foreach (var item in lst)
{
lst1.Add(item[2].ToString());
}
}
private void button1_Click(object sender, EventArgs e) {
if (lst1.Contains(textBox1.Text))
{
// *Need to find that particular item from listbox and clear rest of them*\\
}
}
my input is
1-2-3-4-5
6-7-8-9-10
1-9-4-2-3
7-8-1-4-9
so when textbox has value 7
then my listbox must show 6-7-8-9-10 as output and clear rest all items in listbox
Using what you have posted, I do not understanding what exactly you are trying to achieve. Using the two (2) List’s lst and lst1 looks very odd. Without having more information as to what your ultimate goal is I question why you would do this the way you are.
The code below removes the items in the ListBox where the second character does not match the character in the text box. Hope this helps.
private void button1_Click(object sender, EventArgs e) {
if (lst1.Contains(textBox1.Text)) {
int index = lst1.IndexOf(textBox1.Text);
string temp = listBox1.Items[index].ToString();
MessageBox.Show("Character: " + textBox1.Text + " Found at index: " + index + " the string is: " + temp);
listBox1.Items.Clear();
listBox1.Items.Add(temp);
// *Need to find that particular item from listbox and clear rest of them*\\
} else {
MessageBox.Show("Not Found");
}
}

Selecting Multiple Items From ListBox causes Collection was modified; enumeration operation may not execute

This is a simple code in which i am Transferring Items of one listBox to one Another on btnAdd_Click Event and btnRemove_Click Event resp.
This was working Fine when The selectionMode="Single" and at that point of time i had no need to use foreach inbtn_Add_Click. But Now i've changed selectionMode="Multiple" and used foreach in btnAdd_Click and when i am selecting multiple items from ListBox it is creating the following Error:-
Collection was modified; enumeration operation may not execute
class Movies
{
private Int32 _Id;
private string _movieName;
public Int32 Id
{
get { return _Id; }
set { _Id = value; }
}
public string movieName
{
get { return _movieName; }
set { _movieName = value; }
}
public Movies(Int32 ID, string MovieName)
{
Id = ID;
movieName = MovieName;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Movies> list = new List<Movies>();
list.Add(new Movies(1, "Movie1"));
list.Add(new Movies(2, "Movie2"));
list.Add(new Movies(3, "Movie3"));
list.Add(new Movies(4, "Movie4"));
list.Add(new Movies(5, "Movie5"));
list.Add(new Movies(6, "Movie6"));
list.Add(new Movies(7, "Movie7"));
lstMain.DataSource = list;
lstMain.DataBind();
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
foreach (ListItem list in lstMain.Items)// Here the error comes
{
if(list.Selected)
{
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
}
}
}
protected void btnRemove_Click(object sender, EventArgs e)
{
ListItem list = lstFAvourite.SelectedItem;
lstMain.ClearSelection();
lstMain.Items.Add(list);
lstFAvourite.Items.Remove(list);
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
foreach (ListItem item in lstFAvourite.Items)
{
lbl1.Text += "<li>" + item.Text;
}
}
Please tell me what is going wrong with the foreach loop in btnAdd_Click Event....
Thanks..
You can't remove items from an enumeration while you are looping through it using a foreach, which is what the error message is trying to tell you.
Switching to a straight for loop will get your code to execute:
protected void btnAdd_Click(object sender, EventArgs e)
{
for(var i=0; i<lstMain.Items.Count; i++)
{
var list = lstMain.Items[i];
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
i--;
}
}
However, I believe this code will add all items from lstMain to lstFAvourite. I think perhaps that we should be looking at the Selected property of the ListItem as well in the for loop. For example:
protected void btnAdd_Click(object sender, EventArgs e)
{
for (var i = 0; i < lstMain.Items.Count; i++)
{
var list = lstMain.Items[i];
if(!list.Selected) continue;
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
//Decrement counter since we just removed an item
i--;
}
}
Another method.
lstMain.Items
.Cast<ListItem>()
.ToList()
.ForEach( item =>
{
if(item.Selected)
{
lstFAvourite.Items.Add(item);
lstMain.Items.Remove(item);
}
}
);
lstFAvourite.ClearSelection();
N.B: much slower than the for loop method.
If you try to remove list box items using a for loop using an increment (++) statement, eventually that loop will throw out of bounds error failing to finish removing all the items you want. Use decrement (--) instead.
The error Collection was modified; enumeration operation may not execute is because, while you are deleting the items from the list its affecting the sequence. You need to iterate the items in reverse order for this.
for (int i = lstMain.Items.Count; i > 0; i--)
{
ListItem list = lstMain.Items[i];
lstFAvourite.ClearSelection();
lstFAvourite.Items.Add(list);
lstMain.Items.Remove(list);
}

What control should I use for multiple selection of item in winforms C#?

I am really confused on thinking which control to use for my purpose.
I am having list of items say item1 to item10. User can select 4 or 5 items in any order.
Now user selected items has to be separated in same order.
For example, if the user selected the items in following order, item4, item8, item3 and item2.
I want it in the same order. item4,item8,item3,item2.
How do I achieve this in winforms control?
It is not a very nice solution but I wrote it as you asked.
Set the SelectionMode of your ListBox to MultiExtended or MultiSimple as you need.
Then write this code in SelectedIndexChanged event of your ListBox:
List<string> orderedSelection = new List<string>();
bool flag = true;
private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (flag)
{
flag = false;
var list1 = listBox3.SelectedItems.Cast<string>().ToList();
if (listBox3.SelectedItems.Count > orderedSelection.Count)
{
orderedSelection.Add(list1.Except(orderedSelection).First());
}
else if (listBox3.SelectedItems.Count < orderedSelection.Count)
{
orderedSelection.Remove(orderedSelection.Except(list1).First());
}
var list2 = listBox3.Items.Cast<string>().Except(list1).ToList();
listBox3.Items.Clear();
for (int i = 0; i < list1.Count; i++)
{
listBox3.Items.Add(list1[i]);
listBox3.SelectedIndex = i;
}
foreach (string s in list2)
{
listBox3.Items.Add(s);
}
flag = true;
}
}
When user selects an item, It comes to first of the list and the rest of the items comes next.
Also, there is an alternative way. You can use a CheckedListBox with two extra button for moving selected items up and down. So user can change the order of selected items.
This solution uses CheckListBox's ItemCheck event along with a private List to keep track of the click items order.
protected List<string> clickOrderList = new List<string>();
private void Form1_Load(object sender, EventArgs e)
{
// Populate the checked ListBox
this.checkedListBox1.Items.Add("Row1");
this.checkedListBox1.Items.Add("Row2");
this.checkedListBox1.Items.Add("Row3");
this.checkedListBox1.Items.Add("Row4");
}
private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (sender != null && e != null)
{
// Get the checkListBox selected time and it's CheckState
CheckedListBox checkListBox = (CheckedListBox)sender;
string selectedItem = checkListBox.SelectedItem.ToString();
// If curent value was checked, then remove from list
if (e.CurrentValue == CheckState.Checked &&
clickOrderList.Contains(selectedItem))
{
clickOrderList.Remove(selectedItem);
}
// else if new value is checked, then add to list
else if (e.NewValue == CheckState.Checked &&
!clickOrderList.Contains(selectedItem))
{
clickOrderList.Insert(0, selectedItem);
}
}
}
private void ShowClickOrderButton_Click(object sender, EventArgs e)
{
StringBuilder sb = new StringBuilder();
foreach (string s in clickOrderList)
{
sb.AppendLine(s);
}
MessageBox.Show(sb.ToString());
}

show/ hide items in the listbox

I make a listbox and it works perfectly, I also made a search function, but I want to hide the items in the listbox and show them only when searched through index.
here is my code for adding items
private void Savebtn_Click(object sender, EventArgs e)
{
addTolist(gatherItem());
refreshView();
}
private void addTolist(Person p)
{
Person.listperson.Add(p);
}
private void refreshView()
{
listBox1.Items.Add(getItem());
}
private String getItem()
{
String result = null;
foreach (Person p in Person.listperson)
{
result = p.lastname;
}
return result;
}
and this is my code for search
private void button1_Click(object sender, EventArgs e)
{
int index = listBox1.FindString(textBox6.Text);
if (0 <= index)
{
listBox1.SelectedIndex = index;
}
}
Is there a way for this? thanks :)
There is no easy way to do this with winforms. It a lot easier with WPF. With winforms you will have to remove the items. You could technically use databinding, but its not recommended at all, because listbox is supposed to used directly from your code according the MSDN documentation.
On second thought, you could overdraw the listbox and set the item you want to hide to transparent or something, buts its not easy. You may want to consider storing all your values in an array and then loop through array and only adding the elements you want. Or switch to WPF.
Hope this helps.
You can cover a dummy ListBox on your origin one, and set origin one invisible.
Then you can archive the same effect by writing codes like
class DummyItem {
public string text;
public int index;
public override string ToString() {
return text;
}
}
public void build_dummy() {
listbox_dummy.Items.Clear();
for (int i = 0; i < listbox_origin.Items.Count; i++) {
// replace with your own judgement
if (! should_hide(listbox_origin.Items[i])) {
DummyItem item = new DummyItem();
item.text = listbox_origin.Items[i].ToString();
item.index = i;
listbox_dummy.Items.Add(item);
}
}
}
private void listbox_dummy_SelectedIndexChanged(object sender, EventArgs e) {
var item = (DummyItem) listbox_dummy.SelectedItem;
var index = item.index;
listbox_origin.SelectedIndex = index;
}
The easiest way to do this, is to create a List<string> item that will store removed items (or items that do not match the search-phrase given in textbox1), an int variable that will store how many characters there were the last time the TextChanged event was triggered, and then create a function for your listbox element that activates when the phrase in a textbox is updated:
private void textbox1_TextChanged(object sender, EventArgs e) {}
in this function, there are two things that could happen:
if a character was added to textbox1:
you iterate over the elements in your listbox.
remove the ones that do not contain the phrase in textbox1
if a character was removed from textbox1:
look through the List<string> variable you made to store the values you removed from your listbox
add back each item that fits the text in textbox1 (check for duplicates though)
Here's the code I wrote to use as reference:
private List<string> temporarilyRemovedSongs = new List<string>();
private int previousTextLength = 0;
private void filter_songs_textbox_TextChanged(object sender, EventArgs e)
{
List<string> toRemove = new List<string>();
string text = Tools.Strip(this.filter_songs_textbox.Text.ToLower());
if (text.Length > this.previousTextLength)
{
// a char was added, remove songs that do not start with the search-phrase
foreach (string song in this.songs_list.Items)
{
if (!song.ToLower().Contains(text))
{
this.temporarilyRemovedSongs.Add(song);
toRemove.Add(song);
}
}
foreach (string song in toRemove)
{
this.songs_list.Items.Remove(song);
}
}
else
{
// a char was removed; look through removed songs to add back
foreach (string song in this.temporarilyRemovedSongs)
{
if (song.Contains(text) && !this.songs_list.Items.Contains(song))
this.songs_list.Items.Add(song);
}
}
previousTextLength = text.Length;
}

Categories

Resources