1 2 3 Previous Next 

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

<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF1" Height="300" Width="300"
    >
  <Grid>
    <ListView Margin="25,22,30,48" Name="ListView1" >
      <ListView.View>
        <GridView >
          <GridViewColumn Header ="Last Name" DisplayMemberBinding="{Binding LastName}" Width="100"></GridViewColumn>
          <GridViewColumn Header ="First Name" DisplayMemberBinding="{Binding FirstName}" Width="100"></GridViewColumn>
        </GridView>
      </ListView.View>
    </ListView>
  </Grid>
</Window>


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




WPF OneWay Binding Part 1


Windows Presentation Foundation (WPF) foundation is for building applications and experiences in Windows Vista that blend the application UI, documents, and media content. In this series of blog entries we willl start to explore some of the improvements to data binding in WPF. You will need to have the .Net Framework 3.0, Windows Vista SDK, and Visual Studio 2005 extensions for WPF and WCF installed for this sample.


For this example we will start off with a Windows Application (WPF). In the forms XMAL we will add a stack panel to hold a label and scrollbar. The label's content will be bound to the scrollbar's value so as we move the scrollbar the value will be displayed in the label.


In the Lets set up a DataContext which is bound to the scrollbar .


      <Label   HorizontalAlignment="Center" DataContext="{Binding ElementName=hscroll, Mode=OneWay}"

Now we can bind the label's content to the scrollbars value


      <Label   HorizontalAlignment="Center" DataContext="{Binding ElementName=hscroll, Mode=OneWay}"
               Content="{Binding Path=Value}"  />


The complete XMAL for the Window


<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPFOneWayBind" Height="300" Width="300"
    >
    <Grid>
      <StackPanel>
      <ScrollBar Name="hscroll" Maximum="100"  Minimum="1" SmallChange="1" LargeChange="10" Orientation="Horizontal"></ScrollBar>
      <Label   HorizontalAlignment="Center" DataContext="{Binding ElementName=hscroll, Mode=OneWay}"
               Content="{Binding Path=Value}"  />
      </StackPanel>
    </Grid>
</Window>



OpenXml: Using Linq to XML to create an excel spreadsheet


For this example we are going to create a Excel 2007 spreadsheet using the Microsoft OpenXml Sdk and Linq to XML.

To start with lets create a new Windows forms app which targets the .Net Framework 3.5.  Add a Linq to Sql design surface to your project and name it Northwind and drag the Northwind Products table on to the surface.  On the windows form I added a DataGridview to display the data we are going to export to excel.  We also need a button named btnExport on the form.

To create a excel spreadsheet we need to use the openxml sdk to create a spreadsheet document, workbook, worksheet, and a string table. 

       Using doc = SpreadsheetDocument.Create("Export.xlsx", SpreadsheetDocumentType.Workbook)
            Dim workbook = doc.AddWorkbookPart
            Dim stringTable = workbook.AddNewPart(Of SharedStringTablePart)()
            Dim worksheet = workbook.AddNewPart(Of WorksheetPart)()

The worksheet, workbook, and string table are xml documents contained inside a package.  Before we get to far we need to import a few xml namespaces

Imports <xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
Imports <xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">

Now that we imported the name space we can use some of the new xml features in VB 2008 to create the xml documents.  Since we are not using a string table we just need a blank xml file

Dim xmlStringTable = <sst></sst>

The workbook xml needs to relate the spreadsheet with its id

           Dim xmlWorkbook = <workbook>
                                  <sheets>
                                      <sheet name="Exported" sheetId="1" r:id=<%= sheetId %>></sheet>
                                  </sheets>
                              </workbook>


Note the <%= sheetId %> allows you to get data from a variable

Finally we need to create the worksheet.  In the worksheet we set the column widths and use a linq query to populate the data.

            Dim xmlWorkSheet = <worksheet>
                                   <sheetFormatPr defaultRowHeight="15"/>
                                   <cols>
                                       <col min="1" max="1" width="30" bestFit="1" customWidth="1"/>
                                       <col min="2" max="2" width="10" bestFit="1" customWidth="1"/>
                                   </cols>
                                   <sheetData>
                                       <row>
                                           <c t="inlineStr">
                                               <is>
                                                   <t>Product Name</t>
                                               </is>
                                           </c>
                                           <c t="inlineStr">
                                               <is>
                                                   <t>Unit Price</t>
                                               </is>
                                           </c>
                                       </row>
                                       <%= From p In db.Products Select _
                                           <row>
                                               <c t="inlineStr">
                                                   <is>
                                                       <t><%= p.ProductName %></t>
                                                   </is>
                                               </c>
                                               <c>
                                                   <v><%= p.UnitPrice %></v>
                                               </c>
                                           </row> %>
                                   </sheetData>
                               </worksheet>

Here is the function for writing the xml to the file

   Sub WriteXmlToPart(ByVal part As OpenXmlPart, ByVal x As XElement)
        Dim fs As New IO.StreamWriter(part.GetStream, New System.Text.UTF8Encoding)

        Dim xmlWriter As New Xml.XmlTextWriter(part.GetStream, New UTF8Encoding)
        xmlWriter.Formatting = Xml.Formatting.Indented
        Dim enc As New UTF8Encoding

        xmlWriter.WriteStartDocument()
        x.WriteTo(xmlWriter)
        xmlWriter.WriteEndDocument()
        xmlWriter.Flush()
        xmlWriter.Close()
    End Sub

Here is the complete listing for program

Imports Microsoft.Office.DocumentFormat.OpenXml.Packaging
Imports System.Text
Imports <xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
Imports <xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">

Public Class Form1
    Dim bs As New BindingSource
    Dim db As New NorthwindDataContext

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        bs.DataSource = From p In db.Products _
                        Select p.ProductName, p.UnitPrice

        DataGridView1.DataSource = bs
    End Sub

    Private Sub btnExport_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExport.Click
        Using doc = SpreadsheetDocument.Create("Export.xlsx", SpreadsheetDocumentType.Workbook)
            Dim workbook = doc.AddWorkbookPart
            Dim stringTable = workbook.AddNewPart(Of SharedStringTablePart)()
            Dim worksheet = workbook.AddNewPart(Of WorksheetPart)()
            Dim sheetId = workbook.GetIdOfPart(worksheet)

            'create the string table
            Dim xmlStringTable = <sst></sst>
            WriteXmlToPart(stringTable, xmlStringTable)

            'create the workbook
            Dim xmlWorkbook = <workbook>
                                  <sheets>
                                      <sheet name="Exported" sheetId="1" r:id=<%= sheetId %>></sheet>
                                  </sheets>
                              </workbook>
            WriteXmlToPart(workbook, xmlWorkbook)

            'create the spreadsheet
            Dim xmlWorkSheet = <worksheet>
                                   <sheetFormatPr defaultRowHeight="15"/>
                                   <cols>
                                       <col min="1" max="1" width="30" bestFit="1" customWidth="1"/>
                                       <col min="2" max="2" width="10" bestFit="1" customWidth="1"/>
                                   </cols>
                                   <sheetData>
                                       <row>
                                           <c t="inlineStr">
                                               <is>
                                                   <t>Product Name</t>
                                               </is>
                                           </c>
                                           <c t="inlineStr">
                                               <is>
                                                   <t>Unit Price</t>
                                               </is>
                                           </c>
                                       </row>
                                       <%= From p In db.Products Select _
                                           <row>
                                               <c t="inlineStr">
                                                   <is>
                                                       <t><%= p.ProductName %></t>
                                                   </is>
                                               </c>
                                               <c>
                                                   <v><%= p.UnitPrice %></v>
                                               </c>
                                           </row> %>
                                   </sheetData>
                               </worksheet>

            WriteXmlToPart(worksheet, xmlWorkSheet)

        End Using
    End Sub

    Sub WriteXmlToPart(ByVal part As OpenXmlPart, ByVal x As XElement)
        Dim fs As New IO.StreamWriter(part.GetStream, New System.Text.UTF8Encoding)

        Dim xmlWriter As New Xml.XmlTextWriter(part.GetStream, New UTF8Encoding)
        xmlWriter.Formatting = Xml.Formatting.Indented
        Dim enc As New UTF8Encoding

        xmlWriter.WriteStartDocument()
        x.WriteTo(xmlWriter)
        xmlWriter.WriteEndDocument()
        xmlWriter.Flush()
        xmlWriter.Close()
    End Sub

End Class





WPF OneWay Binding Part 2


In the last part we bound a label to the value of the scrollbar. In this part we will format the scrollbar's value before we display it.


To be able to format the output of a bound value you need a class which inherits from IValueConverter. For this example I am using the NumbersToWords function found here to convert the number to a word for display.



Public Class NumberToWord
    Implements IValueConverter


    Private Function NumbersToWords(ByVal num As Decimal) As String
        Dim power_value(5) As Decimal
        Dim power_name(5) As String
        Dim digits As Integer
        Dim result As String
        Dim i As Integer

        ' Initialize the power names and values.
        power_name(1) = "trillion" : power_value(1) = 1000000000000.0#
        power_name(2) = "billion" : power_value(2) = 1000000000
        power_name(3) = "million" : power_value(3) = 1000000
        power_name(4) = "thousand" : power_value(4) = 1000
        power_name(5) = "" : power_value(5) = 1
        For i = 1 To 5
            ' See if we have digits in this range.
            If num >= power_value(i) Then
                ' Get the digits.
                digits = Int(num / power_value(i))
                ' Add the digits to the result.
                If Len(result) > 0 Then result = result & ", "
                result = result & Words_1_999(digits) & " " & power_name(i)
                ' Get the number without these digits.
                num = num - digits * power_value(i)
            End If
        Next i
        NumbersToWords = Trim$(result)
    End Function

    ' Return words for this value between 1 and 999.
    Private Function Words_1_999(ByVal num As Integer) As String
        Dim hundreds As Integer
        Dim remainder As Integer
        Dim result As String
        hundreds = num \ 100
        remainder = num - hundreds * 100
        If hundreds > 0 Then
            result = Words_1_19(hundreds) & " hundred "
        End If
        If remainder > 0 Then
            result = result & Words_1_99(remainder)
        End If
        Words_1_999 = Trim$(result)
    End Function

    ' Return a word for this value between 1 and 19.
    Private Function Words_1_19(ByVal num As Integer) As String
        Select Case num
            Case 1
                Words_1_19 = "one"
            Case 2
                Words_1_19 = "two"
            Case 3
                Words_1_19 = "three"
            Case 4
                Words_1_19 = "four"
            Case 5
                Words_1_19 = "five"
            Case 6
                Words_1_19 = "six"
            Case 7
                Words_1_19 = "seven"
            Case 8
                Words_1_19 = "eight"
            Case 9
                Words_1_19 = "nine"
            Case 10
                Words_1_19 = "ten"
            Case 11
                Words_1_19 = "eleven"
            Case 12
                Words_1_19 = "twelve"
            Case 13
                Words_1_19 = "thirteen"
            Case 14
                Words_1_19 = "fourteen"
            Case 15
                Words_1_19 = "fifteen"
            Case 16
                Words_1_19 = "sixteen"
            Case 17
                Words_1_19 = "seventeen"
            Case 18
                Words_1_19 = "eightteen"
            Case 19
                Words_1_19 = "nineteen"
            Case Else
                Words_1_19 = ""
        End Select
    End Function

    ' Return a word for this value between 1 and 99.
    Private Function Words_1_99(ByVal num As Integer) As String
        Dim result As String
        Dim tens As Integer
        tens = num \ 10
        If tens <= 1 Then ' 1 <= num <= 19
            result = result & " " & Words_1_19(num)
        Else
            ' 20 <= num
            ' Get the tens digit word.
            Select Case tens
                Case 2
                    result = "twenty"
                Case 3
                    result = "thirty"
                Case 4
                    result = "forty"
                Case 5
                    result = "fifty"
                Case 6
                    result = "sixty"
                Case 7
                    result = "seventy"
                Case 8
                    result = "eighty"
                Case 9
                    result = "ninety"
            End Select
            ' Add the ones digit number.
            result = result & " " & Words_1_19(num - tens * 10)
        End If
        Words_1_99 = Trim$(result)
    End Function

    Public Function Convert(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.Convert
        Dim d As Double
        If Double.TryParse(value.ToString, d) Then
            Return NumbersToWords(CDec(d))
        Else
            Return value
        End If
    End Function

    Public Function ConvertBack(ByVal value As Object, ByVal targetType As System.Type, ByVal parameter As Object, ByVal culture As System.Globalization.CultureInfo) As Object Implements System.Windows.Data.IValueConverter.ConvertBack
        Return Nothing
    End Function
End Class


Now that we created the class we need to register the xml namespace with the window. The namespace you need to use for this is clr-namespace:NamespaceName. In this case it is the applications name. I am adding the local prefix so we can reference it later.


<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WPFOneWayBind"
    Title="WPFOneWayBind" Height="300" Width="300"
    >


Now we need to make the converter a resource for the window.


  <Window.Resources>
    <local:NumberToWord x:Key="conv"></local:NumberToWord>
  </Window.Resources>



Right after we set the path for the binding we can specify the converter. The converter is a StaticResource of the window.


      <Label   HorizontalAlignment="Center" DataContext="{Binding ElementName=hscroll, Mode=OneWay}"
               Content="{Binding Path=Value, Converter = {StaticResource conv}}"  />


Here is the windows complete XAML



<Window x:Class="Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:WPFOneWayBind"
    Title="WPFOneWayBind" Height="300" Width="300"
    >
  <Window.Resources>
    <local:NumberToWord x:Key="conv"></local:NumberToWord>
  </Window.Resources>
    <Grid>
      <StackPanel>
      <ScrollBar Name="hscroll" Maximum="100"  Minimum="1" SmallChange="1" LargeChange="10" Orientation="Horizontal"></ScrollBar>
      <Label   HorizontalAlignment="Center" DataContext="{Binding ElementName=hscroll, Mode=OneWay}"
               Content="{Binding Path=Value, Converter = {StaticResource conv}}"  />
      </StackPanel>
    </Grid>
</Window>




Vista: List Users RSS Feeds


To list the RSS feeds added to IE7 in windows Vista add a reference to Microsoft.Feeds 1.0. You will find it in the com tab. 

Imports Microsoft.Feeds.Interop

Public Class Form1
    Dim mgr As New FeedsManager
    Dim fldr As IFeedFolder

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        fldr = mgr.RootFolder

        ListFeeds(fldr)

    End Sub

    Private Sub ListFeeds(ByVal fldr As IFeedFolder)
        For Each feed As IFeed In fldr.Feeds
            Trace.WriteLine(feed.Name)
            ListItems(feed)
        Next
        For Each f As IFeedFolder In fldr.Subfolders
            Trace.WriteLine(f.Name)
            ListItems(f)
        Next
    End Sub

    Private Sub ListItems(ByVal feed As IFeed)
        Trace.Indent()
        For Each item As IFeedItem In feed.Items
            Trace.WriteLine(item.Title)
        Next
        Trace.Unindent()
    End Sub
End Class




1 2 3 Previous Next