WPF ListBox - how to put values from dataTable?

偶尔善良 提交于 2019-12-22 10:45:29

问题


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


来源:https://stackoverflow.com/questions/1790878/wpf-listbox-how-to-put-values-from-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!