Search code examples
c#winformscomboboxtext-filesstreamreader

how do I put multiple values into a combo box without the separating character appearing?


i'm trying to add data to a combo box, i'm adding an ID and a name, with both appearing on the same line. I'm using ~ to seperate the names and IDs. However I can't figure out how to put these values into a combobox without also adding the ~

try
{
    StreamReader sr = new StreamReader("nameForSkiTimes.txt");
    string line = sr.ReadLine();

    while (line != null)
    {
        addSkiTimesPupilCB.Items.Add(line);
        line = sr.ReadLine();
    }
}

catch (Exception ex)
{
    MessageBox.Show("Error" + ex.Message);
}

I don't really know how to do much in c#, please help.


Solution

  • As your data are delimited with a "~", the easiest way to separate them is using the Split method. Split return an array of strings with the elements (in your case, the ID and the name)

    try
    {
        StreamReader sr = new StreamReader("nameForSkiTimes.txt");
        string line = sr.ReadLine();
        string[] data;
        string label;
    
        while (line != null)
        {
            data = line.Split("~"); // split on "~" char
            if (data.Length > 1) // check if we have at least two elements
            {
                label = $"{data[0]} {data[1]}"; // Access your ID and your name with index, format as you wish
                addSkiTimesPupilCB.Items.Add(label);
            }
            line = sr.ReadLine();
        }
    }
    
    catch (Exception ex)
    {
        MessageBox.Show("Error" + ex.Message);
    }