C#Combobox双数据绑定 - 根据entityframework值选择项目

时间:2016-03-21 20:38:54

标签: c# entity-framework data-binding combobox

我有几个表,使用Entity Framework 6.我的目标是将类table1绑定到ComboBox Value Member

ComboBox DataSource是:

ComboBoxBasicDB[] statType = new ComboBoxBasicDB[] {
            new ComboBoxBasicDB { Text = "A1", Value = 0 },
            new ComboBoxBasicDB { Text = "A2", Value = 1 },
            new ComboBoxBasicDB { Text = "A3", Value = 2 },
            new ComboBoxBasicDB { Text = "A4", Value = 4 },
            new ComboBoxBasicDB { Text = "B12", Value = 12 },
            new ComboBoxBasicDB { Text = "B13", Value = 13 },
            new ComboBoxBasicDB { Text = "B14", Value = 14 }
        };

statBS.DataSource = statType; // statBS == BindingSource, configured throught VS designer, comboBox.DataSource = statBS, comboBox.ValueMember = Value, comboBox.DisplayMember = Text

table1包含名为ex的属性。 Value1包含其中一个(0,1,2,4,12,13,14)

我想要做的是从DB行加载并在TextBox上使用类似的东西:

textBox.DataBindings.Add("Text", binding, "Name");

完美无缺

我试过这样的事情:

comboBox.DataBindings.Add("SelectedValue", binding, "Value1");

但它不起作用,查询后没有选择任何内容。 textBox绑定成功

我使用了SelectedIndex但是有一个问题,那就是7以上的值,因为statType中有7个项目不是14个。

我希望你明白我想做什么:/ 我以为我可以通过comboBox.DataManager但它的私有

来做到这一点

感谢任何想法。

1 个答案:

答案 0 :(得分:0)

所以解决方案是自定义实现,在提到的DataBindings中将SelectedValue更改为SelectedItemValue

实现:

public class ComboBoxBasic : ComboBox
{
    bool diffTextColor = false;

    public ComboBoxBasic()
    {

    }

    public object SelectedItemValue
    {
        get
        {
            return (SelectedItem as ComboBoxBasicDB).Value;
        }

        set
        {
            for(int i = 0; i < Items.Count; i++)
            {
                ComboBoxBasicDB item = Items[i] as ComboBoxBasicDB;

                if(item.Value.ToString() == value.ToString())
                {
                    SelectedIndex = i;

                    break;
                }
            }
        }
    }

    public bool DifferentTextColor
    {
        get { return diffTextColor; }

        set
        {
            diffTextColor = value;

            if (diffTextColor)
            {
                DrawItem += ComboBoxBasic_DrawItem;
                DrawMode = DrawMode.OwnerDrawFixed;
            }
            else
                DrawItem -= ComboBoxBasic_DrawItem;
        }
    }

    void ComboBoxBasic_DrawItem(object sender, DrawItemEventArgs e)
    {
        e.DrawBackground();

        if (e.State == DrawItemState.Focus)
            e.DrawFocusRectangle();

        Brush brush = new SolidBrush((sender as Control).ForeColor);

        ComboBoxBasicDB item = (sender as ComboBoxBasic).Items[e.Index] as ComboBoxBasicDB;

        if (item.ForeColor != Brushes.Black)
            brush = item.ForeColor;

        e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit;
        e.Graphics.DrawString(item.Text, (sender as Control).Font, brush, e.Bounds.X, e.Bounds.Y);
    }
}

如果它由DifferentTextColor

启用,也有自定义DrawItem