Friday, November 28, 2008

WPF: Bind to a ListView

There is not a DataGrid or DataGridView in Windows Presentation Foundation. Use the ListView to display data in a table. In the window's Xaml define the listview and the fields you want displayed. The code behind file is where you get the data from the Northwind database and bind the listview.

The Windows Xaml

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="WPF1" Height="300" Width="300"
>













The Code Behind

Imports System.Data

' Interaction logic for Window1.xaml
Partial Public Class Window1
Inherits System.Windows.Window

Public Sub New()
InitializeComponent()
Dim dt As New DataTable

Dim strConn As String = _
"Server = .\sqlexpress;Database = NorthWind; Integrated Security = SSPI;"
Dim conn As New SqlConnection(strConn)
Dim da As New SqlDataAdapter("Select LastName, FirstName from Employees", conn)
da.Fill(dt)
ListView1.DataContext = dt
Dim bind As New Binding
ListView1.SetBinding(ListView.ItemsSourceProperty, bind)
End Sub

End Class

No comments: