Search code examples
c#formslistboxselectedindex

Automatically select renamed item in a listbox


I have a listbox which contains many items (each item in the listbox comes from a datasource). The items are ordered by name. I have a button in main form. When I choose an item in the listbox and click the button the item will appear in a new form. I can edit selected item's name in the new form. When the new form is closed, the items is already renamed and the listbox is reordered.

How can I automatically re-select the original item which already changed the name and its position in the listbox?

FindString doesn't work because it's already renamed. There is probably a function to use SelectedIndex by using value of item.

Example data:

from [a1, a2, a3, a4, a5] to [ a1, a3, a4, a5, b2 ]


Solution

  • From what I understand, you have FormA that has a list of sorted items. You select an item and press a button to open a new FormB which then renames that item. Once you return to FormA, you would like to have the recently renamed item already selected. The issue that you're having is that you can not find that item in the list using FindString() because the item changed from being named "a2" to "b2" and FindString() does not find "a2" anymore.

    If this is the case, the simple solution is to create a public property on FormB that will store the new name of the item. This process has been explained here: How to return a value from a Form in C#?.

    Example:

    public string ReturnValue1 {get;set;}
    
    private void btnOk_Click(object sender,EventArgs e)
    {
        this.ReturnValue1 = "b2";
        this.Close();
    }
    

    Once you return from FormB, you simply use FindString() with ReturnValue1 to get the index of the item you want to select.

    var result = form.ShowDialog();
    if (result == DialogResult.OK)
    {
        string val = form.ReturnValue1; //value preserved after close
        int index = listBox.FindString(val);
        listBox.SetSelected(index,true);
    }