Alex
Alex

Reputation: 987

DisplayMemberPath for ComboBox in WPF, C#

I have DataTable containing necessary DataRows, which I want to display in ComboBox. The second DataColumn is called VALUE and I want to make it a DisplayMember.

However, all I see in ComboBox - empty lines according to number of DataRows. What am I doing wrong?

DataTable dataTableManufacturers;
dm = new DatabaseManagement.DatabaseManagement(Properties.Settings.Default.DBServer,Properties.Settings.Default.DBName, Properties.Settings.Default.DBUser, Properties.Settings.Default.DBPassword);
dataTableManufacturers = dm.getManufacturers();

combxManufacturer.DisplayMemberPath = "VALUE";

foreach (DataRow row in dataTableManufacturers.Rows)
{
    combxManufacturer.Items.Add(row);
}

Upvotes: 2

Views: 3806

Answers (4)

TYY
TYY

Reputation: 2716

I tried this out and I know for a fact it works.

private DataTable testTable = new DataTable();
        testTable.Columns.AddRange(new DataColumn[]
            {
                new DataColumn("ID", typeof(int)), 
                new DataColumn("Name", typeof(string)), 
            });
        var row = testTable.NewRow();
        row[0] = 1;
        row[1] = "My Name";
        testTable.Rows.Add(row);
        myTestCmb.ItemsSource = TestTable.AsDataView();

<ComboBox x:Name ="myTestCmb" DisplayMemberPath="Name" />

Upvotes: 0

paul
paul

Reputation: 22001

Try setting combxManufacturer.ItemsSource = dataTableManufacturers.Rows; rather than adding the rows individually.

Upvotes: 0

Abdusalam Ben Haj
Abdusalam Ben Haj

Reputation: 5423

Try setting combxManufacturer.ItemsSource property

combxManufacturer.ItemsSource = dataTableManufacturers.AsDataView;

and no need to add items

Upvotes: 0

Jon
Jon

Reputation: 437336

DisplayMemberPath should be "[VALUE]" because you intend to use this indexer (not a property) to get at the data. See binding path syntax on MSDN for more information.

As an (important!) aside, the "WPF way" is to set up the control's ItemSource instead of manually adding to the Items collection.

Upvotes: 4

Related Questions