Instead of associating objects with Combo Box items, I associate long
ids representing choices. They come from a database, so it seems natural to do so anyway. Now, I persist the id
and not the index
of the user's selection, so that the choice is remembered across sessions. If id no longer exists in database - no big deal. The choice will be messed up once. If db does not change, however, then it wo开发者_运维技巧uld be a great success ;)
Here is how I get the id :
chosenSomethingIndex = cmbSomething.GetCurSel();
lastSomethingId = cmbSomething.GetItemData(chosenSomethingIndex);
How do I reverse this? When I load the stored value for user's last choice, I need to convert that id into an index. I can do:
cmbSomething.SetCurSel(chosenSomethingIndex);
However, how can I attempt (it might not exist) to get an index once I have an id?
I am looking for a reciprocal function to GetItemData
I am using VS2008, probably latest version of MFC, whatever that is.
Thank you.
EDIT:
Ah, crap. Looks like I need to do this:
for (int i = 0; i < nCount; i++)
{
if (nId == GetItemData(i))
{
SetCurSel(i);
hr = S_OK;
break;
}
}
You have a function that maps item index to database ID. There is no built-in inverse for that function because the general case doesn't have an inverse. A single data value might map to many different items in the list control; the OS doesn't know your data values are unique.
Your technique of searching the control items one by one is the only way to do it, unless you have additional information stored elsewhere. As you populate your combo box, you could build a reverse index in a std::map
. When you add item i
with database ID id
, add an entry to your other data structure, too:
SetItemData(i, id);
reverse_index[id] = i;
Then, instead of searching one item at a time, you can just look in the index, replacing your loop with this:
std::map<DWORD_PTR, int>::iterator it = reverse_index.find(nId);
if (it != reverse_index.end()) {
assert(GetItemData(*it) == nId);
SetCurSel(*it);
hr = S_OK;
}
SetItemData(DWORD)
or SetItemDatPtr(void*)
IIRC.
精彩评论