I have object names in a ListBox. When a name(line) is clicked, I need to know which line (by number) has been selected. Using that number, I can then do various operations including inserting text into 7 different text boxes. The line number would be the determining number for a switch/case operation. I am using a form setup in C#.
Novice3, Alan

Dani AI

Generated

Building on , and , here are practical, robust tips for turning a selected line into the seven textbox values without making the UI brittle.

Prefer reacting to the control’s selection-changed event rather than only mouse clicks so keyboard or programmatic selections behave the same. Always guard against “no selection” (an invalid index) before doing work. If the control allows multiple selection, decide up front whether the first selected entry is authoritative or whether all selected entries should be processed.

Avoid hard-coded, index-based switch blocks where possible. Two maintainable alternatives:

  • Keep the seven text values with the list data itself (bind a list of small objects that expose seven properties, then copy those properties into the textboxes on selection).
  • Or maintain a small lookup (list/array/dictionary) where each entry is a seven-string group; on selection copy that group into the textboxes. Both patterns make adding, removing, or reordering items far easier than editing a big switch/case.

Add defensive checks and UI concerns: handle nulls/empty strings when assigning textbox text, trim values if needed, and ensure UI updates happen on the UI thread if selection can be triggered from background work. During development, log the resolved row index and the seven assigned values to simplify debugging. If later switching to a different control (for example a ListView), the same data-driven mapping still applies and keeps the code clean.

Recommended Answers

All 3 Replies

Use the SelectedIndex property.

Just to add, remember that arrays are zero based so if you have five items in your list box and select the first item the SelectedIndex proeprty will return zero whereas the last item will return 4.

listBox.Item.SelectedItem for String and
istBox.SelectedIndex for Index.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.