WPF ListBox - how to put values ​​from dataTable?

I have ListBoxand want to put values ​​in this list from DataTable:

listBoxVisibleFields.DataContext = SelectedFields;

Where SelectedFieldsis it DataTablefilled with data. But this code does not work. My is ListBoxempty. As I recall, in WinForms there was such a thing for a list as ValueMemberand DisplayMember, but in WPF I did not find something like this ...

Does anyone know how to fill just mine ListBoxoff DataTable?

+3
source share
2 answers

, , ItemsSource DataContext. , ValueMember, SelectedValuePath (. ). DisplayMember DisplayMemberPath.


EDIT: , :

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

, XAML

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

.

+3

, ,

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()
+1

Source: https://habr.com/ru/post/1723790/


All Articles