【问题标题】:C# databinding combobox to field and populate list from other listC# 数据绑定组合框到字段并从其他列表填充列表
【发布时间】:2016-06-25 12:39:03
【问题描述】:

我有这些课程:

public class City { 
public string name { get; set; } 
public override string ToString() { return name; } 
}
public List<City> cities = new List();
public class Person {
public string name { get; set; }
public string addr { get; set; }
public City city { get; set; }
}
List<Person> persons;

我将城市和人员绑定到bindingSource(以及列表和文本框):

bindingSource_city.DataSource = cities;
textBox1.DataBindings.Add("Text", bindingSource_city, "name");
bindingSource_person.DataSource = person;
textBox2.DataBindings.Add("Text", bindingSource_person, "name");
textBox3.DataBindings.Add("Text", bindingSource_person, "addr");

还有listBox.DataSource = bindingSource(在表单编辑器中)。

似乎一切正常。 如何使用列表中的城市创建组合框并绑定到 person.city 属性? 我不明白如何用对象(不是字符串项)填充下拉列表。

编辑:或者如何在数据(列表索引)更改和返回时将 person.city 转换为 SelectedIndex

【问题讨论】:

  • 谢谢,但这不是答案。在您的示例中,组合框绑定到一个 bindingSource,而我的 - 绑定到两个。

标签: c# winforms data-binding combobox


【解决方案1】:

做起来很简单:

comboBoxCities.DataSource = bindingSource1;
comboBoxCities.DisplayMember = "name";

【讨论】:

  • 它是如何绑定到 person.city 的?我可以填写下拉列表,但我不明白如何将其绑定到属性。
  • 我尝试手动更新列表中的数据,效果很好。我也尝试使用你的代码。它有副作用 - 当我在组合框中更改光标(SelectedIndex)时,第一个列表框中的光标也更改了:)
【解决方案2】:

通过添加事件部分解决:

bindingSouce_city_ListChanges
{
comboBox1.Items.Clear();
foreach( City c in cities ) comboBox1.Items.Add( c );
}
comboBox1_SelectedIndexChanged(...)
{
int i = comboBox1.SelectedIndex;
((Person) bindigSource_person).city = (i < ? null: cities[ i ]);
}
bindingSource_person_CurrentChanged(...)
{
comboBox1.SelectedIndex = 
cities.IndexOf( ((Person) bindingSource_person).city );
}

我认为它不是很好的代码,但它可以工作。

UPD:感谢eugene-podskal 解决办法是:

comboBox1.DataSource = bindinsSource_city;
comboBox1.DataBinding.Add( "SelectedItem", bindingSource_person, "city" );

【讨论】:

  • 您是否尝试将 SelectedItem 上的绑定添加到您所在城市?喜欢stackoverflow.com/questions/31343543/…?
  • 是的!谢谢!这是我想要的!
  • 我需要更新我的答案或问题以获得正确的解决方案吗?
  • 答案是为了答案,问题是为了问题,所以你应该更新答案。只需为您的问题指定一个更具体的标题(当前的标题并未完全描述该问题 - 我会推荐类似“将 ComboBox 的 DataSource 绑定到一个对象并将 SelectedItem 绑定到另一个”的内容),然后添加 [winforms] @ 987654323@给它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
相关资源
最近更新 更多