I have few tables, using Entity Framework 6. My goal is to bind class table1 to ComboBox Value Member
ComboBox DataSource is:
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 contains property called ex. Value1 which contains one of these (0, 1, 2, 4, 12, 13, 14)
What am I trying to do is to load from DB row and use something like this on TextBox:
textBox.DataBindings.Add("Text", binding, "Name");
which works perfectly
I tried something like this:
comboBox.DataBindings.Add("SelectedValue", binding, "Value1");
but it not working, nothing is selected after query. textBox bind successfully
I used SelectedIndex but there is going one problem, and that is value above 7, because there are 7 items in statType not 14.
I hope you understand what am I trying to do :/ I thought I could do that throught comboBox.DataManager but its private
Thanks for any ideas.
So solution is custom implementation, in mentioned DataBindings change SelectedValue to SelectedItemValue
Implementation:
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);
}
}
Also there is custom DrawItem if its enabled by DifferentTextColor
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.