ComboBox数据绑定

kse*_*een 2 .net c# data-binding combobox

我在表单上有一个组合框控件,可以从某些数据源中提取数据(显示和值).另一方面,我有一排桌子.我想在app发布时,组合框将selectedvalue或selecteditem设置为上一行中一列的值.当用户更改了组合框时,它将持续更改为行.我试图将SelectedValue绑定到此列,但它不起作用.Combobox只是开始第一项.有什么问题?


编辑

这是一个Win Forms项目.这是绑定代码:

this.comboBoxCountries = new System.Windows.Forms.ComboBox();
this.countriesBindingSource = new System.Windows.Forms.BindingSource(this.components);

// 
// comboBoxCountries
// 
this.comboBoxCountries.DataBindings.Add(new System.Windows.Forms.Binding("Text", this.searchCriteriaBindingSource, "Postcode", true));
this.comboBoxCountries.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", this.searchCriteriaBindingSource, "CountryCode", true));
this.comboBoxCountries.DataSource = this.countriesBindingSource;
this.comboBoxCountries.DisplayMember = "Name";
this.comboBoxCountries.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBoxCountries.FormattingEnabled = true;
this.comboBoxCountries.Location = new System.Drawing.Point(190, 19);
this.comboBoxCountries.Name = "comboBoxCountries";
this.comboBoxCountries.Size = new System.Drawing.Size(156, 21);
this.comboBoxCountries.TabIndex = 2;
this.comboBoxCountries.ValueMember = "Code";
this.comboBoxCountries.SelectedValueChanged += new System.EventHandler(this.comboBoxCountries_SelectedValueChanged);

// 
// countriesBindingSource
// 
this.countriesBindingSource.DataMember = "Countries";
this.countriesBindingSource.DataSource = this.dbDataSetCountries;
// 
// dbDataSetCountries
// 
this.dbDataSetCountries.DataSetName = "dbDataSetCountries";
this.dbDataSetCountries.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;

// 
// searchCriteriaBindingSource
// 
this.searchCriteriaBindingSource.AllowNew = false;
this.searchCriteriaBindingSource.DataMember = "SearchCriteria";
this.searchCriteriaBindingSource.DataSource = this.dbDataSetSearchCriteria;
this.searchCriteriaBindingSource.BindingComplete += new System.Windows.Forms.BindingCompleteEventHandler(this.searchCriteriaBindingSource_BindingComplete);
// 
// dbDataSetSearchCriteria
// 
this.dbDataSetSearchCriteria.DataSetName = "dbDataSetSearchCriteria";
this.dbDataSetSearchCriteria.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema;
Run Code Online (Sandbox Code Playgroud)

EDIT2

正如我在下面的评论中提到的,我有另一个textbox绑定到另一个DataMember相同的绑定源并且textbox工作正常.它看起来具有适当的价值.当我DataMember在同一个数据库上更改我设置selectedvalue了组合框绑定的属性时,它也显示出良好的结果并且正常工作.

提前致谢!

Ori*_*gin 5

看一下组合框的DisplayMemberValueMember属性.您需要告诉ComboBox数据源中的哪个成员要显示在下拉列表中,以及在请求SelectedValue时要给出的值.

听起来你的ComboBox绑定到一个静态列表,而你的行不是.您可以考虑使用将ComboBox和DataGridView的DataSource设置为的BindingSource.这样,当DGV导航到新行时,ComboBox将使用新行的值进行更新.

以下是MSDN上ComboBox的链接:http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.aspx