Blog Archives

Get Selected Item from ListBox in Winforms C# and VB .Net

Iterate through all items:

  foreach(ListItem item in ListBox1.Items)
    {
       if (item.Selected == True)
       {
          //item.Value //no to be confused with text
          //item.Text //text displayed on UI
       }
    }

Find specific item text:

  private string GetSelectedItem(ListBox container)
        {
            //string selecteditem = "";
            for (int i = 0; i < container.Items.Count; i++)
            {
                if (container.Items[i].Selected == true)
                {
                    //use .value alternatively if you are trying to get value instead of text
                    return ListBox1.Items[i].Text; //breaks the loop or
                    //break; //if you decide to use without a function
                }
            }
            return ""; //error handled in calling func, remove return value if used without a function
            //return selecteditem ; //if you want to iterate all items anyway
        }

More generalized for re-usability to get text or value, though a little less readable and alot more code:

private static class GetSelectedItem {
private enum ListBox_ContentType {
Text,
Value
}

public string Text(ListBox container) { Get_ContentType(container,ListBox_ContentType.Text);}
public string Value(ListBox container) { Get_ContentType(container,ListBox_ContentType.Value);}

private string Get_ContentType(ListBox container, ListBox_ContentType ContentType) {
  for (int i = 0; i < container.Items.Count; i++)
            {
                if (container.Items[i].Selected == true)
                {
if (ContentType == ListBox_ContentType.Value) {
return ListBox1.Items[i].Text;
}
else //ContentType == ListBox_ContentType.Value 
{
                    return ListBox1.Items[i].Value;
}
                }
            }
            return "";
}
}

Bind Control to an Object in Windows Forms

Simple solution for basic binding in Windows Forms app. This would NOT be recommended if you are using ASP .Net, Silverlight, WCF, RIA or any other services to retrieve the data as these project types have much better support for binding to controls.

C#:

static class dataaccess {
static mytype object;
}

//on app load
object = new mytype();

//on form load
tbField1.DataBindings.Add("Text", dataaccess.object.property, "Field1")
Follow

Get every new post delivered to your Inbox.