WPF ListBox - how to put values from dataTable?

2019-05-13 23:02发布

问题:

I have ListBox and want to put values in this listbox from a DataTable:

listBoxVisibleFields.DataContext = SelectedFields;

Where SelectedFields is a DataTable filled with data. But this code does not work. My ListBox is empty. As I remember, in WinForms was sucha a thing for list box like ValueMember and DisplayMember, but in WPF I dont find something like that...

Does someone know how to fill simply my ListBox from DataTable?

回答1:

The property you are looking for is ItemsSource instead of DataContext. The property most closely resembling ValueMember is called SelectedValuePath (see this example). The analogon for DisplayMember is called DisplayMemberPath.


EDIT: So, your code should look like this:

DataTable SelectedFields = ...;
listBoxVisibleFields.SelectedValuePath = "myID";
listBoxVisibleFields.DisplayMemberPath = "myTextField";
listBoxVisibleFields.ItemsSource = SelectedFields.DefaultView;

Alternatively, the two path values can be set in XAML

<ListBox ... SelectedValuePath="myID" DisplayMemberPath="myTextField" />

which is a bit more elegant.



回答2:

Here is my code, hope is usefull

Dim connectionString As String = "Data Source=(local);Database=Catalogos;UID=sa;Password=S1santan"
Dim conSQL As New SqlClient.SqlConnection()
conSQL.ConnectionString = connectionString
conSQL.Open()
Debug.Print("SELECT * FROM CodigoPostal WHERE CP= '" & _Codigo & "'")
Dim adaptSQL As New SqlClient.SqlDataAdapter("SELECT * FROM CodigoPostal WHERE CP= '" & _Codigo & "'", conSQL)

Dim DatosCP As New DataSet
adaptSQL.Fill(DatosCP, "CodigoPostal")

'Here you select the table inside a data set
ListBox1.ItemsSource = DatosCP.Tables("CodigoPostal").DefaultView
'Here select which field to show
ListBox1.DisplayMemberPath = "d_asenta"
'and at last here you select the field you want to use to select values from
ListBox1.SelectedValuePath = "ID"

conSQL.Close()