1

So I'm currently practicing my skills by creating a sample queue-system storing data in a local textfile. I was wondering if I can display a list of tickets on a listbox (queue box).

1 textfile = 1 ticket.

Here is my sample code:

enter image description here

Problems: 1. It displays the ticket number together with the extension name (1005.txt)

  1. It kinda adds to the listbox all the textfiles in the folder. I only wanna show the textfiles as listitems so when I click refresh, it must display the same number of items and not adding duplicates.

Can anyone help me out? Thanks!

2
  • 1
    post your code rather than an image Commented Aug 9, 2017 at 2:44
  • still an image is there :P Commented Aug 9, 2017 at 2:50

2 Answers 2

2

Try this code,

ticketBox.Items.Clear();
DirectoryInfo dinfo = new DirectoryInfo(@"C:\SampleDirectory");
FileInfo[] smFiles = dinfo.GetFiles("*.txt");
foreach (FileInfo fi in smFiles)
{
    ticketBox.Items.Add(Path.GetFileNameWithoutExtension(fi.Name));
}
Sign up to request clarification or add additional context in comments.

Comments

0
private void refreshMainQueue_Click(object sender, EventArgs e)
        {
            /* Comment: I am using lower camelCase for naming convention. */

            /* Comment: Solve your Problem 2: Always clear the list box before populating records. */
            ticketBox.Items.Clear();

            DirectoryInfo dInfo = new DirectoryInfo(@"C:\SampleDirectory");
            FileInfo[] files = dInfo.GetFiles("*.txt");
            /* Comment: Only perform the below logic if there are Files within the directory. */
            if (files.Count() > 0)
            {
                /* Comment: Create an array that has the exact size of the number of files 
                 * in the directory to store the fileNames. */
                string[] fileNames = new string[files.Count()];

                for (int i = 0; i < files.Count(); i++)
                {
                    /* Comment: Solve your Problem 1: 
                     * Refer here to remove extension: https://stackoverflow.com/questions/4804990/c-sharp-getting-file-names-without-extensions */
                    fileNames[i] = Path.GetFileNameWithoutExtension(files[i].Name);
                }

                ticketBox.Items.AddRange(fileNames);
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.