Hi. I'm quite new for c++/cli. I tried to make a ComboBox1 on Form2 which ComboBox1 Bind to MySql Database Table.
Form2 Code
DTab2 = gcnew DataTable();
this->comboBox1->DataSource = DTab2->DefaultView;
this->comboBox1->DisplayMember = "Name";
this->comboBox1->ValueMember = "ID";
....
public:property DataTable ^CB_Prop
{
void set(DataTable ^value){
DTab2 = value;}
DataTable ^get(){
return DTab2;}
}
private:
DataTable ^DTab2;
...
Form1 Code
#include "Form2.h"
...
_Form2 = gcnew Form2();
_Form2->Hide();
String ^ConnString = "server=localhost;user=root;database=MyDB; "
"port=#port;password=passwd;";
MySqlConnection ^Conn = gcnew MySqlConnection(ConnString);
MySqlDataAdapter ^MyAdapt = gcnew MySqlDataAdapter();
MyAdapt->SelectCommand = gcnew MySqlCommand("SELECT ID, Name FROM "
"MyTable", Conn);
DataTable ^DTab1 = gcnew DataTable();
MyAdapt->Fill(DTab1);
_Form2->CB_Prop = DTab1;
}
...
private:
Form2 ^_Form2;
...
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
_Form2->Show();}
The code was Build succeeded but I got error
"An unhandled exception of type 'System.ArgumentException' occurred in System.Windows.Forms.dll"
"Additional information: Cannot bind to the new display member"
I tried to replace
this->comboBox1->ValueMember = "ID";
Form1 and Form2 succeeded initialize but there no items in Combobox1.
I make modification on Form 2 and decide not using DataTable instead DataSet. So I replace DataTable at Form1 and Form2 With DataSet with addition MySqlDataAdapter at Form2
Form2(void)
{
InitializeComponent();
String^ ConnString2 = "server=localhost;user=root;database=MyDB; "
"port=#port;password=passwd;";
MySqlConnection ^Conn2 = gcnew MySqlConnection(ConnString2);
MySqlDataAdapter^ MyAdt2 = gcnew MySqlDataAdapter("SELECT ID, Name "
"FROM MyTable", Conn2);
DSet2 = gcnew System::Data::DataSet();
MyAdt2->Fill(DSet2, "MyTable");
this->comboBox1->DataSource = DSet->Tables["MyTable"];
this->comboBox1->DisplayMember = "Name";
this->comboBox1->ValueMember = "ID";
}
...
public:property DataSet ^CB_Prop
{
void set(DataSet ^value) {
DSet2 = value;}
DataSet ^get() {
return DTab2;}
}
It work and the ComboBox1 filled correctly. But I don't know it's the good way or not.