问题
I would like to display the elements in a vector in a listbox. However, I'm constantly getting a error: error C2664: 'System::Windows::Forms::ListBox::ObjectCollection::Add' : cannot convert parameter 1 from 'std::basic_string<_Elem,_Traits,_Alloc>' to 'System::Object ^'
I am using windows form in c++/cli. this is the code:
for (size_t z = 0; z < container.size(); z++){
listBox_name->Items->Add(container[z]);
}
回答1:
Based on the error message, your vector is a vector of std::string
. Use marshal_as
to convert the std::string
to a managed String^
that the managed list box can accept.
for (size_t z = 0; z < container.size(); z++){
listBox_name->Items->Add(marshal_as<String^>(container[z]));
}
If you find you're doing this a lot, consider changing your vector of std::string
to be a fully-managed type, such as List<String^>^
.
来源:https://stackoverflow.com/questions/22001897/show-vector-elements-in-listbox