Rashmi Patel
Rashmi Patel

Reputation: 27

open text file with key/value into combobox winforms

I am having some difficulty to use a text file that contains key=value entries (ex: ABCD=ABCD) and use a dictionary defined in my C# program to open that file to be used as a combobox.

Below is my current code which I have statically defined the key/value field using add (the whole list has about 30 entries).

Dictionary<string, string> vendors = new Dictionary<string, string>();
vendors.Add("ADVENE", "ADVENE");
vendors.Add("DFG RISK", "DFG RISK");

DataGridViewComboBoxColumn vendcol = new DataGridViewComboBoxColumn();
vendcol.Name = "vendor";
vendcol.HeaderText = "Vendor";
vendcol.DisplayMember = "Value";
vendcol.ValueMember = "Key";
vendcol.DataSource = vendors.ToList();
dataGridView1.Columns.Add(vendcol);

How do I convert the above key/value entries into a text file and have it used by a combobox when opening application?

I have tried to use StreamReader but I am completely lost on how to implement it.

Thanks

Upvotes: 0

Views: 143

Answers (1)

Isma
Isma

Reputation: 15190

Assuming your text file has the following format:

ADVENE=ADVENE
DFG RISK=DFG RISK

You can parse it using the following code:

var vendors = new Dictionary<string, string>();
using (var reader = new StreamReader(@"c:\temp\test.txt"))
{
    string line = string.Empty;
    while ((line = reader.ReadLine()) != null)
    {
        string[] keyValue = line.Split(new char[] { '=' });
        vendors.Add(keyValue[0], keyValue[1]);
    }
}

To populate the DataGridViewColumn you can try the following:

var vendcol = new DataGridViewComboBoxColumn();
vendcol.HeaderText = "Vendor";
vendcol.ValueMember = "Key";
vendcol.DisplayMember = "Value";
vendcol.DataSource = vendors.ToArray();
dataGridView1.Columns.Add(vendcol);

Upvotes: 2

Related Questions