Hi to every one!!!!
For some time now I'm programing in .NET and I have a question in
using ListBox
I need to databind a collection to a ListBox. My code is something
like this:
using namespace System;
using namespace System::Windows::Forms;
ref class MyClass
{
public:
MyClass(String^ strName, String^ strValue)
{
this->m_strName = strName;
this->m_strValue = strValue;
}
property String^ Name
{
String^ get()
{
return this->m_strName;
}
void set(String^ value)
{
this->m_strName = value;
}
}
property String^ Value
{
String^ get()
{
return this->m_strValue;
}
void set(String^ value)
{
this->m_strValue = value;
}
}
private:
String^ m_strName;
String^ m_strValue;
};
System::Collections::Generic::List<MyClass^>^ oMyCollection = gcnew
System::Collections::Generic::List<MyClass^>();
oCollectioon->Add(gcnew MyClass(L"Name1", L"Value1"));
oCollectioon->Add(gcnew MyClass(L"Name2", L"Value2"));
oCollectioon->Add(gcnew MyClass(L"Name3", L"Value3"));
oCollectioon->Add(gcnew MyClass(L"Name4", L"Value4"));
oCollectioon->Add(gcnew MyClass(L"Name5", L"Value5"));
ListBox^ oListBox = gcnew ListBox();
oListBox->DataSource = oCollectioon;
oListBox-DisplayMember = L"Name";
oListBox->ValueMember = ???;
oListBox->SelectedValueMember = ????;
My question is:
How can I bind the collection oMyCollection to the ListoxBox
displaying the Name property of my MyClass but the ValueMember and
SelectedValueMember are the collection item itself?
Thanks
NAlexVS
Ben Voigt [C++ MVP] - 12 Sep 2007 16:42 GMT
> Hi to every one!!!!
>
[quoted text clipped - 66 lines]
> displaying the Name property of my MyClass but the ValueMember and
> SelectedValueMember are the collection item itself?
Did you try not changing those properties at all?
Also, you probably want to use a BindingList<T> instead of List<T>
caracolito1975@gmail.com - 12 Sep 2007 16:57 GMT
> <caracolito1...@gmail.com> wrote in message
>
[quoted text clipped - 74 lines]
>
> Also, you probably want to use a BindingList<T> instead of List<T>
Thanks!!!
I'll try your solution using a BindingList
Regards
Ben Voigt [C++ MVP] - 12 Sep 2007 17:08 GMT
>> <caracolito1...@gmail.com> wrote in message
>>
[quoted text clipped - 77 lines]
> Thanks!!!
> I'll try your solution using a BindingList
BindingList will simply cause the ListBox to automatically reflect new
elements added or removed from the collection.
No matter what collection you use, the SelectedItem property should always
be the actual data object, and not just a single property as
DisplayMember/ValueMember/SelectedValueMember are concerned with. So use
SelectedItem instead of SelectedValue.
> Regards