What's new

C# Load, Search and Clear Items in ListBox [Tutorial 5]

zackmark29

Forum Expert
Elite
Joined
Mar 25, 2013
Posts
4,237
Solutions
23
Reaction
10,687
Points
2,301
Here's the function that we are going to use:

First of all, take note yung functions na gagamitin natin nasa ibaba:

First:
//declare this as global variable
List<string> allItems = new List<string>();

LOAD ITEMS:
C#:
private void button1_Click(object sender, EventArgs e)
{
   var items = LoadItemsToListBox();
   //add items to listbox
   AddListBoxItems(items.ToArray());
   //store the items from listbox
   allItems.AddRange(listBox1.Items.Cast<string>().ToList());
}

METHOD 1:

HERE'S THE TEXTBOX SEARCH:
//REFER TO SEARCH ITEMS FUNCTION 2
C#:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    //clear the items first when start typing
    listBox1.Items.Clear();

    //here we search the items from allItems
    var items = SearchItem(allItems, textBox1.Text);
    AddListBoxItems(items);

    if (listBox1.Items.Count > 0)
    {
        listBox1.SetSelected(0, true); //select the result item
    }
    //now if the searchbox is empty, we can restore the old items from allitems
    if (string.IsNullOrEmpty(textBox1.Text))
    {
        listBox1.SelectedItems.Clear();
        AddListBoxItems(allItems);
    }
}

METHOD 2:

TEXTBOX SEARCH:
//REFER TO SEARCH ITEMS FUNCTION 1
C#:
private void textBox1_TextChanged(object sender, EventArgs e)
{
    SearchItem(textBox1.Text);
}



FUNCTIONS:

LOAD ITEMS TO LISTBOX FROM FILE DIALOG:

C#:
private IEnumerable<string> LoadItemsToListBox()
{
    using (var ofd = new OpenFileDialog() {
        Filter =
        "Audio Files (*.mp3, *.mp4, *.wmv, *.m4a) | *.mp3; *.mp4; *.wmv; *.m4a" +
        "|Video Files (*.mp4, *.mkv, *.ts, *.flv, *.m4v) | *.mp4; *.mkv; *.ts; *.flv, *.m4v" +
        "|Image Files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png" +
        "|Text Files (*.txt) | *.txt" +
        "|All Files (*.*) | *.*",
        Multiselect = true,
        RestoreDirectory = true,
        //AutoUpgradeEnabled = false //kung gusto mo old windows xp style enable mo
    })
    {
        List<string> items = new List<string>();

        if (ofd.ShowDialog() == DialogResult.OK)
        {
            var fileName = ofd.FileNames;
            foreach(var name in fileName) {
                //store the names to lists
                items.Add(Path.GetFileName(name));
            }
        }
        return items;
    }
}

ADD ITEMS TO LISTBOX
C#:
private void AddListBoxItems(IEnumerable<string> items)
{
    listBox1.BeginUpdate();
    listBox1.Items.AddRange(items.ToArray()
        .Where(x => !listBox1.Items.Cast<string>()
        .Any(item => x.Equals(item, StringComparison.InvariantCultureIgnoreCase))).ToArray());
    listBox1.EndUpdate();
    CountListBoxItems();
}

SEARCH ITEMS FUNCTION 1
C#:
private void SearchItem(string searchItem) {
//clear existing items
  listBox1.Items.Clear();
  for (int i = listBox1.Items.Count - 1; i >= 0; i--) {
    if (listBox1.Items[i].ToString().Contains(searchItem)) {
      listBox1.SetSelected(i, true);
    }
    else {
      listBox1.Items.RemoveAt(i);
    }
  }
  if (string.IsNullOrEmpty(textBox1.Text)) {
    listBox1.SelectedItems.Clear();
    AddListBoxItems(allItems);
  }
}

SEARCH ITEM FUNCTION 2:
C#:
//here's the function. you can make static for global use
private IEnumerable<string> SearchItem(IEnumerable<string> items, string searchString)
{
    return items.Cast<string>().ToList().Where(x => x.Contains(searchString)).ToArray();
}
 
Last edited:
1603445682008.png

1603445715875.png

Ts. Di na bumalik yung mga files na nilagay ko isa nalang ulit pag nag search ako ng hindi tugma sa isa nawawala nanaman .... Pa help..
 

Attachments

View attachment 997129
View attachment 997130
Ts. Di na bumalik yung mga files na nilagay ko isa nalang ulit pag nag search ako ng hindi tugma sa isa nawawala nanaman .... Pa help..

Anong method ginamit mo?

did you put this: List<string> allItems= new List<string>(); as global var?
Diyan kasi naka store ang old items

dapat babalik ang old items once empty na ang search box

if (string.IsNullOrEmpty(textBox1.Text)) {
listBox1.SelectedItems.Clear();
AddListBoxItems(allItems);
}
 
Anong method ginamit mo?

did you put this: List<string> allItems= new List<string>(); as global var?
Diyan kasi naka store ang old items

dapat babalik ang old items once empty na ang search box

if (string.IsNullOrEmpty(textBox1.Text)) {
listBox1.SelectedItems.Clear();
AddListBoxItems(allItems);
}
Ts. Pa try nga mp4 or mp3 file extension yung ilagay mo sa listbox mo then search mo... ok lang ba?
 

Kaya pala, hindi talaga masstore yung items kasi di mo ginamit tong codes:

C#:
 private void LoadItems()
        {
            using (var ofd = new OpenFileDialog() {
                Filter =
                "Audio Files (*.mp3, *.mp4, *.wmv, *.m4a) | *.mp3; *.mp4; *.wmv; *.m4a" +
                "|Video Files (*.mp4, *.mkv, *.ts, *.flv, *.m4v) | *.mp4; *.mkv; *.ts; *.flv, *.m4v" +
                "|Image Files (*.jpg, *.jpeg, *.png) | *.jpg; *.jpeg; *.png" +
                "|Text Files (*.txt) | *.txt" +
                "|All Files (*.*) | *.*", 
                Multiselect = true, 
                RestoreDirectory = true,
                //AutoUpgradeEnabled = false //kung gusto mo old windows xp style enable mo
            })
            {
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    var items = new List<string>();
                    var fileName = ofd.FileNames;
                    foreach(var name in fileName) {
                        items.Add(Path.GetFileName(name));
                    }
                 
                    AddListBoxItems(items.ToArray());
                    allItems.AddRange(listBox1.Items.Cast<string>().ToList());
                }
            }
        }

yan ang gamitin mo instead of this:

C#:
 private void button3_Click(object sender, EventArgs e)
        {

            OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
            OpenFileDialog1.Multiselect = true;
            if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                files = OpenFileDialog1.SafeFileNames;
                paths = OpenFileDialog1.FileNames;
                for (int i = 0; i < files.Length; i++)
                {
                    listBox1.Items.Add(files[i]);
                }
            }
        }
 
Last edited:
By the way, you can change your code for loading and playing the url

from this:
C#:
private void button2_Click(object sender, EventArgs e)
{
    axWindowsMediaPlayer1.URL = textBox_path.Text;
    axWindowsMediaPlayer1.Ctlcontrols.play();
}

to this:
C#:
private void button2_Click(object sender, EventArgs e)
{
    foreach (var item in listBox1.SelectedItems)
    {
        var url = item.ToString();
        textBox_path.Text = url;
        axWindowsMediaPlayer1.URL = url;
        axWindowsMediaPlayer1.Ctlcontrols.play();
    }
}
 
Back
Top