C# - 填充组合框与一个DataTable [英] C# - Fill a combo box with a DataTable
问题描述
我已经习惯了与Java工作的地方都可以大量的例子。由于种种原因,我不得不切换到C#和尝试做以下的SharpDevelop的:
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 ;(
编辑: mnuActionLanguage.ComboBox.DataBind()是我还发现,在网上,但它不能在我的情况下工作。的
mnuActionLanguage.ComboBox.DataBind() is what I also found on the net, but it doesn't work in my case.
解决方案:
mnuActionLanguage.ComboBox.BindingContext = this.BindingContext;
在最后的问题解决了!
at the end solved the problem!
推荐答案
您需要设置ToolStripComboBox.ComboBox的绑定上下文。
You need to set the binding context of the ToolStripComboBox.ComboBox.
下面是我刚才使用Visual Studio重新创建code稍微修改后的版本。菜单项组合框被称为toolStripComboBox1在我的情况。注code中的最后一行,设置绑定上下文。
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?
如果你不能得到这个工作,通过我的联系页面给我写信,我会送你的项目。您将无法使用SharpDevelop的加载,但会用C#防爆preSS。
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;
这篇关于C# - 填充组合框与一个DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!