有没有办法在不使用数据源的情况下为组合框分配值?

时间:2014-05-14 13:54:29

标签: c# winforms entity-framework

我正在使用Entity Framework将一个组合框与我的MSSQL数据库中的值一起使用以下

using (var context = new Entity())
{
    var things = (from p in context.Stuff 
                  where ((p.SourceId == StuffId && p.Domain.Value == "Stuff") 
                    || (p.SourceId == OtherStuffId && p.Domain.Value == "OtherStuff")) 
                    && p.Done == true orderby p.StuffId 
                  select p);

    foreach(var stuff in things)
        cboRejectTask.Items.Add(stuff.StuffId + ": " + stuff.StuffType.Description + " " + stuff.StuffType.DisplayName);
}

我想为每一行分配值,以便在获取用户选择的内容时,我不必进行字符串操作以获得我想要的内容。如果可能,我不想使用数据源。

解决方案

鉴于没有比创建自定义类更好的方法,我继续使用所选答案的代码进行了修改,以便长期使用。 (注意:只要ToString()返回“显示文本”并且它有一个Tag或任何可写属性与您的需求兼容,您就可以使用任何给定的对象)

public class ComboBoxItem
{
    public string Display;
    public object Value;

    public override string ToString()
    {
        return Display;
    }
}

鉴于此代码,我现在可以将代码更改为以下内容:

using (var context = new Entity())
{
    var things = (from p in context.Stuff 
                  where ((p.SourceId == StuffId && p.Domain.Value == "Stuff") 
                    || (p.SourceId == OtherStuffId && p.Domain.Value == "OtherStuff")) 
                    && p.Done == true orderby p.StuffId 
                  select p);

    foreach(var stuff in things)
        cboRejectTask.Items.Add(new ComboBoxItem() { Display = stuff.StuffId + ": " + stuff.StuffType.Description + " " + stuff.StuffType.DisplayName, Value = stuff.StuffId });
}

2 个答案:

答案 0 :(得分:2)

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        var cbi1 = new ComboBoxItem("Item 1") { Id = 1 };
        var cbi2 = new ComboBoxItem("Item 2") { Id = 2 };
        var cbi3 = new ComboBoxItem("Item 3") { Id = 3 };
        comboBox1.Items.Add(cbi1);
        comboBox1.Items.Add(cbi2);
        comboBox1.Items.Add(cbi3);
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var id = ((ComboBoxItem)comboBox1.SelectedItem).Id;

        MessageBox.Show(id.ToString());

    }
}

public class ComboBoxItem
{
    private readonly string text;

    public int Id { get; set; }

    public ComboBoxItem(string text)
    {
        this.text = text;
    }

    public override string ToString()
    {
        return text;
    }
}

答案 1 :(得分:0)

我想你可能会觉得这很有用:

comboBox1.Items.Add(1);
comboBox1.Items.Add(2);
comboBox1.Items.Add(3);

private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
    //this will set what gets displayed in the combobox, but does not change the value.
    e.Value = "display value";
}

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    MessageBox.Show((sender as ComboBox).SelectedItem.ToString());
}