我无法在 ComboBox 中以编程方式设置选择。我尝试设置各种属性(SelectedItem、SelectedText、SelectedIndex),但 ComboBox 不显示名称。ComboBox 的第一行是空白的,被选中。属性设置的返回值是正确的。我究竟做错了什么?...this.bsConstructionContractors.DataSource = typeof(Contractor);...public partial class EditContractorDialog : Form{ public EditContractorDialog(Contractor contractor) { InitializeComponent(); this.cmbEditContractorName.DataBindings.Add(new System.Windows.Forms.Binding("SelectedValue", projectView.bsProject, "ContractorId", true)); // new BindingSource is important here, so as to use a separate CurrencyManager // because bsConstructionContractors is shared with another ComboBox on another form this.cmbEditContractorName.DataSource = new BindingSource(projectView.bsConstructionContractors, null); this.cmbEditContractorName.ValueMember = "ContractorId"; this.cmbEditContractorName.DisplayMember = "Name"; cmbEditContractorName.Enabled = true; cmbEditContractorName.Focus(); // None of the following cause the ComboBox to display Contractor.Name // The first entry in the ComboBox, which is a blank, is displayed object myObject = cmbEditContractorName.SelectedItem = contractor; System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject: " + myObject.GetType()); // type is Contractor System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject: " + myObject); // myObject is the contractor object myObject2 = cmbEditContractorName.SelectedText = contractor.Name; System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject2: " + myObject2.GetType()); // type is String System.Diagnostics.Trace.WriteLine("EditContractorDialog(): myObject2: " + myObject2); // myObject2 is the contractor.Name }}
2 回答
茅侃侃
TA贡献1842条经验 获得超21个赞
那是因为您需要从组合框本身的 DataSource 中获取要分配的对象引用。同样对于组合框,我建议您使用ObservableCollection<T>.
cmbEditContractorName.DataSource = new ObservableCollection<Type>(your List<Type>);
cmbEditContractorName.SelectedItem = ((ObservableCollection<Type>)cmbEditContractorName.DataSource).FirstOrDefault(c=> c.yourProperty = "something"); // this will select the first item meeting your condition
您的代码不起作用,因为您正在SelectedItem使用组合框中不存在的对象的引用分配属性DataSource。
- 2 回答
- 0 关注
- 205 浏览
添加回答
举报
0/150
提交
取消