C# - Unable to populate combobox with text file contents

I'm trying to write a program in C# that will allow my users to install printers quickly in our organization.

Currently the form is set up like this:



I would like people to be able to select a server in the Print Server drop down menu which would then populate the Printer Name menu with the printers from that server.

My form load code looks like this:

private void AddPrinterForm_Load(object sender, EventArgs e)
        {           
            this.PrintServerBox.Items.Add("server1");
            this.PrintServerBox.Items.Add("server2");
            this.PrintServerBox.Items.Add("server3");
            this.PrintServerBox.Items.Add("server4");
            this.PrintServerBox.Items.Add("server5");
            this.PrintServerBox.Items.Add("server6");
        }

Open in new window


The Printer Name drop down is supposed to populate from a txt file that lists the printer names in order on their own line when a server is selected.

My SelectedIndexChanged event looks like this:

private void PrintServerBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            PrinterNameBox.Items.Clear();
            if (PrintServerBox.SelectedItem.ToString() == "server1")
            {
                StreamReader sr = new StreamReader(@".\server1Printers.txt");
                string x = sr.ReadToEnd();
                string[] y = x.Split('\n');
                foreach (string s in y)
                {
                    PrinterNameBox.Items.Add(s);
                }

            }

Open in new window


Unfortunately, this does not populate the menu.

I've also tried doing it unsuccessfully like this:

private void PrintServerBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            PrinterNameBox.Items.Clear();
            if (PrintServerBox.SelectedItem.ToString() == "server1")
            {
                
                string[] lineOfContents = File.ReadAllLines(@".\server1Printers.txt");
                foreach (var line in lineOfContents)
                {
                   string[] tokens = line.Split(',');
                    PrinterNameBox.Items.Add(tokens[0]);
                }
                
            }

Open in new window


Neither one of these worked. I have added the text files to the program itself.

Does anyone have any suggestions on how I can populate that Printer Name box?
LVL 1
Jason ParadisIT Operations SpecialistAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Nitin SontakkeDeveloperCommented:
Did you debug already and see that the data is coming? Is it right at the end i.e. in drop down it is not listed?

Unfortunately, I have almost never have added items like this. How about having a List<String> and then add it as a datasource and then databind? Do not forget to initialize "DisplayMember" and "ValueMember".
0
Nitin SontakkeDeveloperCommented:
While your code worked very well without alteration at my end you may still wish to modify as follows:

    private void PrintServerBox_SelectedIndexChanged(object sender, EventArgs e)
    {
      PrinterNameBox.Items.Clear();
      if (PrintServerBox.SelectedItem.ToString() == "server1")
      {
        StreamReader sr = new StreamReader(@".\server1Printers.txt");
        string x = sr.ReadToEnd();
        string[] y = x.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        foreach (string s in y)
        {
          PrinterNameBox.Items.Add(s);
        }
      }
    }

Open in new window


Incidentally, did you actually clicked and checked in Printers drop down?
0
NorieAnalyst Assistant Commented:
What do you actually have in the text file?
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Jason ParadisIT Operations SpecialistAuthor Commented:
I'm fairly new to programming so I'll have to see if I can find out how to do that. Once I figure it out and it works I'll make sure to tag it as best solution.

Thanks!
0
Jason ParadisIT Operations SpecialistAuthor Commented:
A list of printer names on their own line. The names match what's on the server.
0
Jason ParadisIT Operations SpecialistAuthor Commented:
@Nitin

I tried your changed code and it didn't work. The Printer Name box continues to stay empty. Am I supposed to put the text files in a specific place? All I did was right-click the program name in Solution Explorer and click Add.

You're saying my original code worked as well? I must be doing something wrong here.
0
Nitin SontakkeDeveloperCommented:
I had used following and worked very well for me!

Printer 1
Printer 2
Printer 3
Printer 4
Printer 5
Printer 6

Open in new window

0
Shaun VermaakTechnical SpecialistCommented:
    private void PrintServerBox_SelectedIndexChanged(object sender, EventArgs e)
    {
            PrinterNameBox.Items.Clear();
            if (PrintServerBox.SelectedItem.ToString() == "server1")
            {
                string[] lines = File.ReadLines(@".\server1Printers.txt").ToArray();
                foreach (string line in lines)
                {
                    PrinterNameBox.Items.Add(line);
                }
            }
    }

Open in new window

0
NorieAnalyst Assistant Commented:
If you have a separate file for each printer you could try something like this.
    private void PrintServerBox_SelectedIndexChanged(object sender, EventArgs e)
    {

       if (string.IsNullOrEmpty(PrintServerBox.Text))
      {
           MessageBox.Show("No Server is Selected"); 
      }
     else
     {
      PrinterNameBox.Items.Clear();

      StreamReader sr = new StreamReader(@".\"+PrintServerBox.Text+"Printers.txt");
      string x = sr.ReadToEnd();
      string[] y = x.Split(new Char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
      foreach (string s in y)
        {
           PrinterNameBox.Items.Add(s);
         }
      }
    }
    

Open in new window

0
Nitin SontakkeDeveloperCommented:
Aha! Right click on that file, select 'Properties' from the context sensitive menu. Then change 'Copy to Output Directory' to Copy if newer.

Also, if you are me, use path as follows:

StreamReader sr = new StreamReader(AppDomain.CurrentDomain.BaseDirectory + "\\server1Printers.txt");

Open in new window

0
Jason ParadisIT Operations SpecialistAuthor Commented:
@Nitin

I had my text file set up exactly like that. I click the server1 selection and nothing populates in the Printer Name combobox.

I also already changed the properties to Copy If Newer.

@Shaun

I tried your code as well and nothing populates in the combobox.

@Norie

I do have multiple servers on separate files. I just made continuing else if statements after the initial if one for each text file. I will give your version a go.
0
Jason ParadisIT Operations SpecialistAuthor Commented:
I'm still not able to get anything to populate. I'm about ready to just do a big block of manual Adds in the code just to see if it actually works.

Here's one thing I didn't mention: I actually copied the form and all components from a VB solution that I was creating. I wanted to do it in C# for the experience. Could that be causing the problem? I checked all of the naming and it seems fine. I didn't copy the code, just the form and controls.

I just don't understand why it's not populating that combobox no matter what I do. It's acting like nothing happens when I click the server1 option in the first drop-down.
0
NorieAnalyst Assistant Commented:
Jason

Have you tried setting up breakpoints at appropriate points and stepping through the code to see what's happening/not happening?
0
Jason ParadisIT Operations SpecialistAuthor Commented:
Yep. I insert the breakpoint in the SelectedIndex change event and nothing happens. It works in the form load event. But not the one that matters.
0
NorieAnalyst Assistant Commented:
Jason

Do you mean the SelectedIndexChanged event isn't being fired?
0
Jason ParadisIT Operations SpecialistAuthor Commented:
I believe you're correct.

I've even done the sample code on this page but nothing happens. The second drop down never populates: http://csharp.net-informations.com/gui/cs-combobox.htm

Combobox SelectedIndexChanged event

The SelectedIndexChanged event of a combobox fire when you change the slected item in a combobox. If you want to do something when you change the selection, you can write the program on SelectedIndexChanged event. From the following code you can understand how to set values in the SelectedIndexChanged event of a combobox. Drag and drop two combobox on the Form and copy and paste the following source code.

using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            comboBox1.Items.Add("weekdays");
            comboBox1.Items.Add("year");
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            comboBox2.Items.Clear();
            if (comboBox1.SelectedItem == "weekdays")
            {
                comboBox2.Items.Add("Sunday");
                comboBox2.Items.Add("Monday");
                comboBox2.Items.Add("Tuesday");
            }
            else if (comboBox1.SelectedItem == "year")
            {
                comboBox2.Items.Add("2012");
                comboBox2.Items.Add("2013");
                comboBox2.Items.Add("2014");
            }
        }
    }
}

Open in new window


Nothing happens. The second drop down never populates. I don't get it.
0
NorieAnalyst Assistant Commented:
Jason

When you have the combobox selected when in design view do you see anything against SelectedIndexChanged in the Events section of the Property sheet?

If the event is set up correctly you should see comboboxname_SelectedIndexChanged.

Also, if you add a combobox to a form and double click it the code stub for it's 'default' event should be generated, it would look something like this.
    private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Jason ParadisIT Operations SpecialistAuthor Commented:
@Norie

That was it! I went into the Events section of the combobox property and there was nothing in the SelectedIndexChanged property. I changed it to the PrintServerBox_SelectedIndexChanged setting and it's working now. Was that supposed to be done already by Visual Studio or do I have to do that every time with comboboxes?

Or at least, it's working with the individual ones I put in there. Now to test with the text files.

Thank you!

EDIT: It worked with the text file and my original code! Thanks you're a lifesaver!
0
Nitin SontakkeDeveloperCommented:
Was that supposed to be done already by Visual Studio or do I have to do that every time with comboboxes?

Well, yes, but this time because you just copied and pasted the code it just didn't become apparent.

Typically we (most developers) just go there, let VS create the handler for us and then type in the code.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming

From novice to tech pro — start learning today.