C# - 用数据表填充组合框 [英] 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.BindingContext = this.BindingContext;
最后解决了问题!
推荐答案
需要设置ToolStripComboBox.ComboBox的绑定上下文.
You need to set the binding context of the ToolStripComboBox.ComboBox.
这是我刚刚使用 Visual Studio 重新创建的代码的略微修改版本.在我的例子中,菜单项组合框称为 toolStripComboBox1.请注意设置绑定上下文的最后一行代码.
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# Express.
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# - 用数据表填充组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!