Mar*_*lon 13 c# data-binding combobox business-objects winforms
快速问题,是否可以将组合框绑定到对象列表,但是将selectedvalue属性指向对象,而不是对象的属性.
我只是问,因为我们有一些Business Objects引用了其他对象 - 比如'Year'对象.那年的对象可能需要换掉另一年的对象.
我能想到的唯一解决方案是让另一个类具有单个属性,在这种情况下指向年份对象.然后将组合框绑定到这些的列表,并将显示和值成员设置为单个属性.
但是,对于任何"查找",我们这样做似乎有点痛苦?
马龙
jms*_*era 26
如果将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());
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用DataSource属性将 ComboBox 绑定到任何值列表。或者实际上:
实现 IList 接口的对象,例如 DataSet 或 Array。默认值为空。
然后使用ValueMember来控制从SelectedValue获得的内容。将此设置null为jmservera写入可让您获得DataSource.
| 归档时间: |
|
| 查看次数: |
48359 次 |
| 最近记录: |