C# - Fill a combo box with a DataTable

MrG picture MrG · Nov 2, 2008 · Viewed 227.5k times · Source

I'm used to work with Java where large amounts of examples are available. For various reasons I had to switch to C# and trying to do the following in SharpDevelop:

// Form has a menu containing a combobox added via SharpDevelop's GUI

// --- Variables
languages = new string[2];
languages[0] = "English";
languages[1] = "German";
DataSet myDataSet = new DataSet();

// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add( lName );
for( int i=0; i<languages.Length; i++ ) {
    DataRow lLang = lTable.NewRow();
    lLang["Language"] = languages[i];
    lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);

// --- Handling the combobox
mnuActionLanguage.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
mnuActionLanguage.ComboBox.DisplayMember = "Language";

One would assume to see some values in the dropdown, but it's empty. Please tell me what I'm doing wrong ;(

EDIT: mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.

SOLUTION

mnuActionLanguage.ComboBox.BindingContext = this.BindingContext;

at the end solved the problem!

Answer

BlackWasp picture BlackWasp · Nov 2, 2008

You need to set the binding context of the ToolStripComboBox.ComboBox.

Here is a slightly modified version of the code that I have just recreated using Visual Studio. The menu item combo box is called toolStripComboBox1 in my case. Note the last line of code to set the binding context.

I noticed that if the combo is in the visible are of the toolstrip, the binding works without this but not when it is in a drop-down. Do you get the same problem?

If you can't get this working, drop me a line via my contact page and I will send you the project. You won't be able to load it using SharpDevelop but will with C# Express.

var languages = new string[2];
languages[0] = "English";
languages[1] = "German";

DataSet myDataSet = new DataSet();

// --- Preparation
DataTable lTable = new DataTable("Lang");
DataColumn lName = new DataColumn("Language", typeof(string));
lTable.Columns.Add(lName);

for (int i = 0; i < languages.Length; i++)
{
    DataRow lLang = lTable.NewRow();
    lLang["Language"] = languages[i];
    lTable.Rows.Add(lLang);
}
myDataSet.Tables.Add(lTable);

toolStripComboBox1.ComboBox.DataSource = myDataSet.Tables["Lang"].DefaultView;
toolStripComboBox1.ComboBox.DisplayMember = "Language";

toolStripComboBox1.ComboBox.BindingContext = this.BindingContext;