I was working on this the other day. At least, working a way to use the FindbyText and FindbyIndex features to get some of the heavy lifting I wanted done. In this case I was using a combobox to manage selection options, had a dbgrid slaved to it to show deeper details for the one-line selection it provided, and have an option for individuals to indicate they wanted to save their option (out of a possible many) to a nearby listbox. Now I wanted to be sure they didn't add multiples of the same type of selection from the combobox, a very common requirement, so I used FindbyText to search the item collection of the listbox. In this case, I was looking for a "no match" result so I would know to add an item. Here's a sample of the code:
if (listbox.Items.FindByText(combobox.SelectedText) == null)
{
listbox.Items.Add(combobox.SelectedText);
}
As you can guess, it returns a null value if nothing is found (not always the case, I might add). If you are looking for a "match" then switch it to the following:
if (listbox.Items.FindByText(combobox.SelectedText) != null)
Just as a note, if you want to remove something that's been selected, say for a context menu or button that allows for it; or, for times when you have are looking for a positive find and want to take action, like removing a selected item from a list box, use the following line of code:
listbox.Items.RemoveBySelection('Y');
It takes a boolean value, obviously and you could easily flip it to 'N'. Good when you might need to toggle the ability to remove an item based on permissions.
Now, I realize I haven't covered FindbyIndex yet. you can use it to find items in a list or combo box thought its not as handy necessarily. You would need to do the comparison outside first and then match it up by index and then perform a listbox.Items.FindbyIndex(Index).
Here is a much better use of findbyindex. As a way to reset a combo/listbox back to its first entry:
if(combobox.Items.Count > 0)
{
combobox.SelectedText = combobox.Items.FindByIndex(0);
}
No comments:
Post a Comment