C# tutorials
23. Adding items to a ComboBox at run-time

Note: While reading this page, bear in mind that I'm no computer expert and that the text below may be partly inaccurate. If you find errors or have proposals for improvements, please send me a message and help make this a better page for the benefit of future visitors. To the left, there are links to more C# tutorials.


To complete this tutorial, follow these instructions:

1. Open Visual C# 2010 Express.

2. Click on New Project in the File menu.

3. Choose Windows Forms Application if that option isn't already chosen, change the name if you like and click on OK.

4. Point at Toolbox in the left margin and click on the Auto Hide icon at the top of the window (to keep the window to stay open and easier to work with).

5. Drag two Buttons, a ComboBox, a TextBox and two RichTextBoxes to Form 1.

6. Right-click on the ComboBox and click on Properties.

7. In the Properties pane, change DropDownStyle to DropDownList.

8. In the Properties pane, select Items and click on the button with three dots to the right of (Collection).

9. Write New user-defined or something similar in the textbox in the String Collection Editor and click on OK.

10. Double-click on Form1 and write or paste this code where the caret is (make sure to not click on a Button, the ComboBox, the TextBox or a RichTextBox):

try
{
  comboBox1.SelectedIndex = 0;
  if (File.Exists(file))
  {
    StreamReader sr = new StreamReader(file, Encoding.GetEncoding(65001));
    string str = sr.ReadToEnd().TrimEnd('‡');
    sr.Close();
    string[] arr = str.Split('‡');
    foreach (string item in arr)
    {
      string[] getItem = item.Split('†');
      comboBox1.Items.Add(getItem[0]);
    }
  }
}
catch (Exception excMsg)
{
  MessageBox.Show(excMsg.Message.ToString(), "Error");
}

11. Double-click on button1 and write or paste this code where the caret is:

try
{
  if (textBox1.Text == string.Empty)
  {
    MessageBox.Show("Type something in textBox1 and try again.");
    return;
  }
  else if (richTextBox1.Text == string.Empty)
  {
    MessageBox.Show("Type something in richTextBox1 and try again.");
    return;
  }
  else
  {
    comboBox1.Items.Add(textBox1.Text);
    StreamWriter sw = new StreamWriter(file, true, Encoding.GetEncoding(65001));
    sw.Write(textBox1.Text + '†' + richTextBox1.Text + '‡');
    sw.Close();
    textBox1.Clear();
    richTextBox1.Clear();
  }
}
catch (Exception excMsg)
{
  MessageBox.Show(excMsg.Message.ToString(), "Error");
}

12. Double-click on button2 and write or paste this code where the caret is:

try
{
  int i = comboBox1.SelectedIndex;
  comboBox1.Items.RemoveAt(i);
  comboBox1.SelectedIndex = (i - 1);
  StreamReader sr = new StreamReader(file, Encoding.GetEncoding(65001));
  string str = sr.ReadToEnd().TrimEnd('‡');
  sr.Close();
  string[] arr = str.Split('‡');
  StringBuilder sb = new StringBuilder();
  foreach (string item in arr)
  {
    if (item != arr[i - 1])
    {
      sb.Append(item + '‡');
    }
  }
  if (sb.ToString() == string.Empty)
  {
    File.Delete(file);
    return;
  }
  else
  {
    StreamWriter sw = new StreamWriter(file, false, Encoding.GetEncoding(65001));
    sw.Write(sb.ToString());
    sw.Close();
    return;
  }
}
catch (Exception excMsg)
{
  MessageBox.Show(excMsg.Message.ToString(), "Error");
}

13. Double-click on comboBox1 and write or paste this code where the caret is:

try
{
  if (comboBox1.SelectedIndex == 0)
  {
    button1.Visible = true;
    button2.Visible = false;
    textBox1.Visible = true;
    richTextBox1.Visible = true;
  }
  else
  {
    button1.Visible = false;
    button2.Visible = true;
    textBox1.Visible = false;
    richTextBox1.Visible = false;
    int i = (comboBox1.SelectedIndex - 1);
    StreamReader sr = new StreamReader(file, Encoding.GetEncoding(65001));
    string str = sr.ReadToEnd().TrimEnd('‡');
    sr.Close();
    string[] arr = str.Split('‡');
    string[] getContents = arr[i].Split('†');
    richTextBox2.Text = getContents[1];
  }
}
catch (Exception excMsg)
{
  MessageBox.Show(excMsg.Message.ToString(), "Error");
}

14. Write or paste this code right below using System.Windows.Forms;:

using System.IO;

15. Write or paste this code right above the line private void Form1_Load(object sender, EventArgs e):

string file = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"comboBoxTutorial.txt";

16. Make sure you don't have a file called comboBoxTutorial.txt on the desktop. You most likely don't, but if you do rename that file or it may be overwritten or deleted when you're running this program.

17. Press F5 to start debugging the program.

18. Click on button1. A MessageBox with the text Type something in textBox1 and try again. should appear.

19. Close the MessageBox, type something in textBox1, for example XML and click on button1. A MessageBox with the text Type something in richTextBox1 and try again. should appear.

20. Close the MessageBox, type something in richTextBox1, for example <?xml version="1.0" encoding="UTF-8"?> and click on button1.

21. Click on comboBox1. The item XML or whatever you typed in textBox1 should appear right below the item New user-defined or whatever you typed in the textbox in the String Collection Editor.

22. Select the item XML. The following should happen:

23. Go to the desktop and open the file comboBoxTutorial.txt. The contents should be:

XML†<?xml version="1.0" encoding="UTF-8"?>‡

24. Click on button2. The following should happen:

25. Go to the desktop. The file comboBoxTutorial.txt should no longer be there.

Comments on the first code snippet

Line 3-15: Things the program does when it's started.

Line 3: Set the selected index for comboBox1 to 0 (New user-defined or whatever you typed in step 9). If you skip this line, the visible part of comboBox1 will be empty at first.

Line 4-15: Check if the file with user definitions exists, get the contents if it does, and fill comboBox1 with whatever the user has typed in textBox1 and saved.

Line 6: Encoding 65001 is UTF-8 with signature (byte order mark). You should use that encoding so that any sign can be used in user-defined ComboBox items.

Line 7: Remove the last ‡. If you don't, you will get an empty item at the bottom of the ComboBox.

Line 9: Make an array of the text the user has saved.

Line 12-13: Split each value in the array by †, and add the first value in the new array (the title, so to speak) to comboBox1.

Comments on the second code snippet

Line 3-7: Show a message if textBox1 (for text to display in comboBox1) is empty.

Line 8-12: Show a message if richTextBox1 (for text to display in richTextBox2) is empty.

Line 15-20: Save a new user-defined item for comboBox1.

Line 15: Display the title of the new item in comboBox1.

Line 16: true is append, false overwrite. You want to keep what's already saved, so you're using true. Encoding 65001: see comment to line 6 in the first code snippet.

Line 17: The rarely used sign † is used to separate title and contents. The even more rarely used sign ‡ is used to separate items. You may use other signs you're sure the user won't use. [note]The sign † appears 1 time and the sign ‡ 0 times in a 13.5 million words big corpus I collected from 845 websites between November 2008 and August 2009.

Line 19-20: Clear textBox1 and richTextBox1 to make it easier to add new items.

Comments on the third code snippet

Line 3-29: Remove a user-defined item from comboBox1 and comboBoxTutorial.txt or whatevever you've called the file.

Line 3-4: Get the selected item in comboBox1 and remove it.

Line 5: Display the item right above the item you removed in line 3-4.

Line 6-9: Get the contents of comboBoxTutorial.txt and transform it to an array.

Line 10-17: Make a new StringBuilder and append each item in the array that isn't the item you want to remove.

Line 18-22: If the StringBuilder sb is empty a.k.a. the last user-defined item is removed, delete comboBoxTutorial.txt.

Line 23-29: If the StringBuilder sb isn't empty, save the string.

Line 25: true is append, false overwrite. You want to overwrite what's already saved, so you're using false. Encoding 65001: see note to line 6 in the first code snippet.

Comments on the fourth code snippet

Line 3-9: If the option in comboBox1 is New user-defined or whatever you typed in step 9, make these forms visible:

and this form invisible:

Line 10-23: If the option in comboBox1 isn't New user-defined or whatever you typed in step 9, display the contents of the selected item in richTextBox2.

Line 12-15: Make this form visible:

and these forms invisible:

Line 17-20: Get the contents of comboBoxTutorial.txt and transform it to an array.

Line 21: Make an array of the value in the array arr that corresponds to the selected item in the combobox.

Line 22: Display the second value in the array getContents (the contents part) in richTextBox2.

Comment on the fifth code snippet

File, StreamReader and StreamWriter need the namespace System.IO to work.

Comment on the sixth code snippet

Normally, you don't save a settings file, like comboBoxTutorial.txt, to the SpecialFolder Desktop but rather to the SpecialFolder ApplicationData. I decided to use the desktop in this tutorial, because I think it makes the file easier to find in case you want to open it or need to delete it.


Would you like to comment on this page or some other page? Use the contact form. Write the title of the page you want to comment on and your comment in the field Message.