Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF ListBox - how to put values from dataTable?

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?

like image 280
Vytas Avatar asked Dec 05 '25 18:12

Vytas


2 Answers

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.

like image 165
Heinzi Avatar answered Dec 08 '25 16:12

Heinzi


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()
like image 20
Otacon Avatar answered Dec 08 '25 14:12

Otacon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!