Martin Nikolaev
Martin Nikolaev

Reputation: 243

ListBox selected item refer to a variable

Here what I've done.

I made my own class.

public class Node
{
    public string name;
    public string type;
    public string vm_name;
    public string vm_ip;
    public string vm_hostname;
}

string[] nodes = new string[2];
Node vm1 = new Node();
Node vm2 = new Node();

I set Name property:

vm1.name = "name1";
vm2.name = "name2";

I put all variables from this type in a string

nodes[0] = vm1.name;
nodes[1] = vm2.name;

After that I added that array into the listbox items

nodeList.Items.AddRange(nodes);

Is there a way to access the variable by selecting the item from the list box ?

If there is a better way to do it I am open for suggestions.

Upvotes: 0

Views: 260

Answers (2)

Selman Genç
Selman Genç

Reputation: 101732

Use DisplayMember and DataSource properties.And create an array of Nodes instead of strings,

var nodes = new []
 { 
    new Node { name = "name1" },
    new Node { name = "name2" }
 }

nodeList.DisplayMember = "name";
nodeList.DataSource = nodes;

Then you can access your SelectedItem and cast it to Node like this:

private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
    var selectedNode = nodeList.SelectedItem as Node;

    if (selectedNode != null)
    {
       ...
    }
}

Upvotes: 2

Cam Bruce
Cam Bruce

Reputation: 5689

Bind the listbox directly to the Node instance instead of a string.

var node = (Node) nodeList.SelectItem;

Upvotes: -1

Related Questions