Question Binding DataSource on control created at runtime?

tim8w

Well-known member
Joined
Sep 8, 2020
Messages
131
Programming Experience
10+
I am using a custom MultiColumnComboBox created by Nish Nishant. I would like to define in during runtime, not design time and am having problems with binding the datasource, I believe. Here is the code for the DataTable and the MultiColumnCoboBox with my attempt to bind them together:

C#:
                    DataTable myDataTable = new DataTable("Defaults");
                    myDataTable.Columns.Add("DefectCode", typeof(string));
                    myDataTable.Columns.Add("DefectName", typeof(string));

                    myDataTable.Rows.Add(new string[] { "A01:", "Damage Leadwires/Sleeving" });
                    myDataTable.Rows.Add(new string[] { "A01-a:", "Damaged convolute tubing" });
                    myDataTable.Rows.Add(new string[] { "A01-b:", "Damaged Insulation" });
                    myDataTable.Rows.Add(new string[] { "A01-c", "Damaged Shrink Tubing" });
                    
                    MultiColumnComboBox myMultiColumnComboBox = new MultiColumnComboBox();
                    myMultiColumnComboBox.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.SuggestAppend;
                    myMultiColumnComboBox.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.ListItems;
                    myMultiColumnComboBox.DataBindings.Add(new Binding("Text", myDataTable, "DefectCode", true));
                    myMultiColumnComboBox.DataSource = myDataTable;
                    myMultiColumnComboBox.DisplayMember = "DefectCode";
                    myMultiColumnComboBox.ValueMember = "DefectName";
                    myMultiColumnComboBox.DrawMode = DrawMode.OwnerDrawVariable;

The problem I have is that when it is defined this way at runtime, the DataManager is undefined. What am I doing wrong? I know you'll probably say to reach out to Nish, but he has not responded.
 
Add the control to form right after you create it, before adding data source.

Adding DataBindings for Text property is not needed, DisplayMember is what is shown as text for selected bound item.
 
Add the control to form right after you create it, before adding data source.

Adding DataBindings for Text property is not needed, DisplayMember is what is shown as text for selected bound item.
John,
The control is added in Runtime right after the form is created. I just added the line:

C#:
myMultiColumnComboBox.DataBindings.Add(new Binding("Text", myDataTable, "DefectCode", true));

recently to see if that helped. Removing that line does not help. The DataManager is still null when the code hits the line:

C#:
myMultiColumnComboBox.DataSource = myDataTable;
 
You have to add the control to form before adding data source.
 
Solution
Back
Top Bottom