Get selected and set selected in ListBox

// Loop through all items the ListBox.

for (int x = 0; x < listBox1.Items.Count; x++){

// Determine if the item is selected.

if(listBox1.GetSelected(x) == true)

// Deselect all items that are selected.

listBox1.SetSelected(x,false);

else

// Select all items that are not selected.

listBox1.SetSelected(x,true);

}

Check if TreeNode is selected

TreeNode tn = treeView1.SelectedNode;

if(tn == null)

Console.WriteLine(“No tree node selected”);

else

Console.WriteLine(“Selected tree node {0}”, tn.Name);

Get text of selected items in a listbox

foreach(var item in listBox1.SelectedItems){

MessageBox.Show(item.ToString());

}