Home > OS >  How to add to a listBox only the left part of dictionary<string, string>?
How to add to a listBox only the left part of dictionary<string, string>?

Time:10-14

At the top of the form

Dictionary<string, string> FileList = new Dictionary<string, string>();

In the constructor

public Form1()
{
    InitializeComponent();
      
    if (System.IO.File.Exists(Path.Combine(path, "test.txt")))
    {
        string g = System.IO.File.ReadAllText(Path.Combine(path, "test.txt"));
        FileList = JsonConvert.DeserializeObject<Dictionary<string, string>>(g);
        listBox1.DataSource = FileList.ToList();
    }

instead making :

listBox1.DataSource = FileList.ToList();

and then in the listBox i will see for example "hello", "d:\test\test1.txt"

I want that in the listBox there will be only : "hello"

I don't want to change the FileList but to change what will be adding from the FileList to the listBox and that is only the left side.

another problem might be with the listBox selected index :

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    var item = ((ListBox)sender).SelectedItem;
    var itemCast = (KeyValuePair<string, string>)item;
    pictureBox1.Image = System.Drawing.Image.FromFile(itemCast.Value);
}

in one hand i don't want to see in the listBox the right side the values in the other hand i want the selected index event to be working.

CodePudding user response:

I'm guessing that, when the user selects a key, you're going to want to get the corresponding value. In that case, rather than just binding the keys, bind the whole Dictionary:

myListBox.DisplayMember = "Key"
myListBox.ValueMember = "Value"
myListBox.DataSource = myDictionary

Each item is a KeyValuePair, which has Key and Value properties. The code above will display the keys and then, when the user selects an item, you can get the corresponding value from the SelectedValue property.

CodePudding user response:

A dictionary maps keys to values. What you call "left part/side" is actually the key, and the other element is the value.

C# Dictionary has a property: Keys which returns only the keys in the dictionary (e.g. your "hello" string).

Therefore you can use:

listBox1.DataSource = FileList.Keys.ToList();

Note that if you ever need only the values (e.g. "d:\test\test1.txt" etc.), Dictionary has a similar property: Values.

  • Related