2010-09-22 37 views
10

快速問題,是否可以將組合框綁定到對象列表,但將selectedvalue屬性指向對象,而不是對象的屬性。c#與對象列表綁定的combobox綁定

我只問,因爲我們有一些業務對象引用了其他對象 - 例如「年」對象。那年的對象可能需要切換爲另一年的對象。

我唯一能想到的解決方案是讓另一個類具有一個屬性,在這種情況下指向一個年份對象。然後將組合框綁定到這些列表並將顯示和值成員都設置爲單個屬性。

但是,對於任何「查找」,我們似乎有點痛苦?

馬龍

回答

20

如果設置ValueMember爲null選擇的值將永遠是對象,而不是一個屬性:

{ 
    public class TestObject 
    { 
     public string Name { get; set; } 
     public int Value { get; set; } 
    } 
    public partial class Form1 : Form 
    { 
     private System.Windows.Forms.ComboBox comboBox1; 

     public Form1() 
     { 
      this.comboBox1 = new System.Windows.Forms.ComboBox(); 
      this.SuspendLayout(); 
      // 
      // comboBox1 
      // 
      this.comboBox1.FormattingEnabled = true; 
      this.comboBox1.Location = new System.Drawing.Point(23, 13); 
      this.comboBox1.Name = "comboBox1"; 
      this.comboBox1.Size = new System.Drawing.Size(121, 21); 
      this.comboBox1.TabIndex = 0; 
      this.comboBox1.SelectedValueChanged += new System.EventHandler(this.comboBox1_SelectedValueChanged); 
      // 
      // Form1 
      // 
      this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); 
      this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; 
      this.ClientSize = new System.Drawing.Size(284, 262); 
      this.Controls.Add(this.comboBox1); 
      this.Name = "Form1"; 
      this.Text = "Form1"; 
      this.ResumeLayout(false); 

      BindingList<TestObject> objects = new BindingList<TestObject>(); 
      for (int i = 0; i < 10; i++) 
      { 
       objects.Add(new TestObject() { Name = "Object " + i.ToString(), Value = i }); 
      } 
      comboBox1.ValueMember = null; 
      comboBox1.DisplayMember = "Name"; 
      comboBox1.DataSource = objects; 
     } 

     private void comboBox1_SelectedValueChanged(object sender, EventArgs e) 
     { 
      if (comboBox1.SelectedValue != null) 
      { 
       TestObject current = (TestObject)comboBox1.SelectedValue; 
       MessageBox.Show(current.Value.ToString()); 
      } 
     } 
    } 
} 
+3

如果我用這個方法,我不能編程設置的SelectedValue,我不得不用'的SelectedItem '。 – AdamMc331 2015-09-04 15:40:02

3

您可以將組合框綁定到使用DataSource屬性值的任何名單。或者實際上:

實現IList接口的對象,如DataSet或Array。缺省值爲空。

然後,您使用ValueMember來控制從SelectedValue得到的結果。設置爲nulljmservera寫入可讓您獲取對象,如同在DataSource中一樣。