Kala J
Kala J

Reputation: 2070

How can I bind an attribute from db table to combobox WPF?

Here's my combo box:

<ComboBox
                HorizontalAlignment="Left"
                Margin="125,110,0,0"
                VerticalAlignment="Top"
                Width="120"
                SelectedValue="{Binding LotNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                ItemsSource="{Binding LotNumber}"
                RenderTransformOrigin="0.583,2" Height="18" />

Here's my property for LotNumber:

private string lotNumber;
public string LotNumber
    {
        get
        {
            return lotNumber;
        }
        set
        {
            lotNumber = value;
            RaisePropertyChanged("LotNumber");
        }
    }

Right now lot number attribute is under my lotInformation table.

E.g. (excerpt of class, class has another properties)

public class LotInformation
{
    [XmlAttribute("lot_number")]
    public string lot_number { get; set; }

}

So, my dbset is:

public DbSet<LotInformation> LotInformation {get;set;}

The binding for combobox is empty. Nothing gets binded... I'm not sure why. Should I be using ComboBox_Loaded?

Basically, I just want to display all the lot numbers that are currently present inside the database.

Upvotes: 0

Views: 665

Answers (2)

Rachel
Rachel

Reputation: 132568

You are binding ItemsSource to LotNumber, which is a string. The expected value for ItemsSource is a collection of objects to display in the dropdown.

Since string is not "a collection of objects", your binding is probably failing.

What you want to do is create a collection of available values (use a List<string> if your collection is static, or an ObservableCollection<string> if the collection is dynamic and can be changed at runtime) and bind your ItemsSource property to that

<ComboBox ItemsSource="{Binding AllAvailableLotNumbers}"
          SelectedItem="{Binding LotNumber}" />

Upvotes: 2

rajibdotnet
rajibdotnet

Reputation: 1596

ItemsSource is of type IEnumerable, so you need to pass it the lotInformation table(some sort of collection of LotNumbers). For binding you need to set the properties as shown :-

<ComboBox             
DisplayMemberPath="LotNumber"
ItemsSource="{Binding lotInformation }"/>

Upvotes: 1

Related Questions