Skip to main content

How to: Filter a LookUp(ComboBox) Column Based on Another Column Value

  • 3 minutes to read

This example shows how to manually filter a lookup editor’s popup data source based on the value of another lookup editor. The solution described is applicable to both standalone and in-place editors. However, for standalone editors you can use the automatic filtering feature instead, covered in the Cascading Lookups topic.

Assume that a Data Grid contains two columns that should allow an end-user to select countries and cities from dropdown lists. When a certain country is selected in the first column, the second column’s dropdown list should only provide cities from the selected country. To display the only appropriate values, the second column’s values should be filtered based on the first column’s value.

GridControl-ShownEditor2Example.gif

This task can be easily implemented if the second column’s in-place editor is a look-up editor (LookUpEditBase descendant).

Handle the ColumnView.ShownEditor event, which fires after an in-place editor has been activated in any grid cell. Use this event to filter the list of items to be displayed in the look-up editor’s dropdown and assign this list to the editor’s RepositoryItemLookUpEditBase.DataSource property.

View Example

using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using System;
using System.Collections.Generic;
using System.Linq;

namespace DxSample {
    public partial class MainForm : XtraForm {
        public MainForm() {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e) {
            this.PhonesSource.DataSource = DataContext.GetPhones();
            this.CountriesSource.DataSource = DataContext.GetCountries();
            this.CitiesSource.DataSource = DataContext.GetAllCities();
        }

        private void GridView_ShownEditor(object sender, EventArgs e) {
            ColumnView view = (ColumnView)sender;
            if (view.FocusedColumn.FieldName == "CityCode") {
                LookUpEdit editor = (LookUpEdit)view.ActiveEditor;
                string countryCode = Convert.ToString(view.GetFocusedRowCellValue("CountryCode"));
                editor.Properties.DataSource = DataContext.GetCitiesByCountryCode(countryCode);
            }
        }

        // In certain scenarios you may want to clear the secondary editor's value
        // You can use the RepositoryItem.EditValueChanged event for this purpose
        private void CountryEditor_EditValueChanged(object sender, EventArgs e) {
            this.GridView.PostEditor();
            this.GridView.SetFocusedRowCellValue("CityCode", null);
        }
    }
}
See Also