Search code examples
c#databasefile-iocomboboxfile-read

c# - Reading a complex file into a comboBox


So I tried some research, but I just don't know how to google this..

For example, I got a .db (works same as .txt for me) file, written like this:

DIRT: 3;
STONE: 6;

so far, i got a code that can put items in a comboBox like this:

DIRT,
STONE,

will put DIRT and STONE in the comboBox. This is the code I'm using for that:

        string[] lineOfContents = System.IO.File.ReadAllLines(dbfile);
        foreach (var line in lineOfContents)
        {
            string[] tokens = line.Split(',');
            comboBox1.Items.Add(tokens[0]);
        }

How do I expand this so it put e.g. DIRT and STONE in the combobox, and keep the rest (3) in variables (ints, like int varDIRT = 3)? If you want, it doesn't have to be txt or db files.. i heard xml are config files too.


Solution

  • Try doing something like this:

                cmb.DataSource = File.ReadAllLines("filePath").Select(d => new
                {
                    Name = d.Split(',').First(),
                    Value = Convert.ToInt32(d.Split(',').Last().Replace(";",""))
                }).ToList();
                cmb.DisplayMember = "Name";
                cmb.ValueMember= "Value";
    

    remember it will require to use using System.Linq; if your want ot reference the selected value of the combobox you can use cmb.SelectedValue; cmb.SelectedText;