Take the 2-minute tour ×

I am making a project in winforms. I have a listbox that is populated on the run, with custom class objects from a list. For each object, I have an associated button. I want the program to return one of the properties of the associated object in the listbox, when the button is clicked. I also want to select the item in the listbox.

Population of listbox:

 private void UpdateList()

The event that is fired when clicking the associated button:

associatedButton.MouseUp += (sender, eventArgs) =>
    Button btn = (Button)sender;
    for (int j = 0; j < listbox.Items.Count; j++)
        if (listbox.GetItemText(j) == btn.Tag.ToString())
            listbox.SelectedItem = j;

The point of this code would be, to get either the MyObject.id property (which is a string) of the given object in the list, or the displayed text in the listbox for that item (these two are identical). btn.Tag is also created to store the string id value of the corresponding object. But listbox.GetItemText(j) (or listbox.Items(j).ToString()) does not seem to return any value. It does not throw an exception, but the if construct is simply skipped. Any solution for this?

share|improve this question
I don't understand what you mouse up event is trying to do, it seems like its trying to set the selected item instead of retrieving the details of it. Try setting a breakpoint and looking at values –  Sayse Aug 18 at 7:33
I did. Returning the value is needed for the if statement. It has no value, that is my problem. –  zergerge Aug 18 at 7:39
Returning what value/where? Set multiple breakpoints and take a look at the values at different points –  Sayse Aug 18 at 7:41
:sigh: I set breakpoints, yes, and I checked it step-by-step. Problem is, that listbox.GetItemText(j), or the variants listed below in the question, does not have a value, or simply return an empty string. –  zergerge Aug 18 at 7:45
I am looking for something like listbox.Items(j).object_property . –  zergerge Aug 18 at 7:46

Your Answer



Browse other questions tagged or ask your own question.