Search code examples
c#devexpress

DevExpress LookupEdit setting EditValue does not work


I'm trying to get the LookUpEdit to show an initial value when the form is displayed. I'm binding a list of countries as the datasource and then setting the EditValue when the form loads which should show the country as the selected item in the LookUpEdit. Unfortunately, it just shows an empty value. The LookUpEdit appears to otherwise work and allows me to scroll through the list of countries and select an item and the value is passed back when I submit the form.

The Country class:

public class Country
{
    public Country();
    public int CountryId {get; set;}
    public string CountryName {get; set;}
    public string IsoCode {get; set; }
}

The code behind the form containing the LookUpEdit:

this.country.Properties.DataSource = this.Countries;
this.country.Properties.DisplayMember = "CountryName";
this.country.Properties.ValueMember = "CountryId";

this.country.EditValue = initialCountry;
this.country.DataBindings.Add("EditValue", viewModel.Address, "AddressCountry", false, DataSourceUpdateMode.OnPropertyChanged);

In this example this.Countries is a populated List<Country> and initialCountry is set to an instance of Country and viewModel.Address contains a property Country AddressCountry.

I've tried both setting the EditValue directly only and setting the data binding to EditValue on it's own as well. Whatever I try, the LookUpEdit is always blank when the form loads and I need it to be set to the initialCountry. I'm sure it's something really simple but I'm not seeing it so any help is much appreciated.


Solution

  • You should not set this.country.EditValue to an instance of Country, but to CountryId, since this is your ValueMember.

    this.country.EditValue = initialCountry.CountryId;
    

    EDIT: if you want to get the selected object you should use GetDataSourceRowByKeyValue

    var selectedCountry = this.country.GetDataSourceRowByKeyValue(this.country.EditValue) as Country;