Locations of visitors to this page


Onteora Software - Linq

Onteora Software

Ken Tucker's Blog

About the author

Author Name is someone.
E-mail me Send mail

Recent posts

Recent comments

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2008

Datagridview and Linq issue

I had some one ask me an interesting question about using linq with the datagridview

When I bind a datagridview to this query

Dim names() As String = {"hello11", "hello212", "hello123", "hello124", "hello2325", "hello336", "hello457"}
Dim query = From s In names _
            Order By s _
            Select s
Dim bs As New BindingSource
bs.DataSource = query
DataGridView1.DataSource = bs

Why do I get these results?

image

The answer the datagridview will show the properties of the class in the list bound to the datagridview.  In this case we are bound to a list of string and the only bindable property is its Length.  

If you change the query to this

Dim names() As String = {"hello11", "hello212", "hello123", "hello124", "hello2325", "hello336", "hello457"}
Dim query = From s In names _
            Order By s _
            Select New With {.Name = s}
Dim bs As New BindingSource
bs.DataSource = query
DataGridView1.DataSource = bs

You will get the expected results

image  

I should also mention that you can not bind a datagridview to a linq query directory.  You need to bind the query to a bindingsource and bind the datagridview to the bindingsource or bind the datagridview to the queries ToList method.



kick it on DotNetKicks.com

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | Linq | VB
Posted by Ken Tucker on Monday, January 28, 2008 6:35 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Use Linq to create a random list of numbers

Here is a simple linq query which places the numbers from 1 and 150 in a random order

 

Dim r As New Random(Now.Ticks Mod Int32.MaxValue)

Dim rndLst = From l In (From num In Enumerable.Range(1, 150) _
             Select New With {.Num = num, .pos = r.Next(1, 150)}) _
             Order By l.pos _
             Select l.Num

For Each i In rndLst
    Console.WriteLine(i)
Next


kick it on DotNetKicks.com

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Linq | VB | VS 2008
Posted by Ken Tucker on Monday, December 03, 2007 2:14 PM
Permalink | Comments (1) | Post RSSRSS comment feed

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


kick it on DotNetKicks.com

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Linq | xml | open xml
Posted by Ken Tucker on Sunday, November 25, 2007 4:30 AM
Permalink | Comments (1) | Post RSSRSS comment feed

Linq to DataSet

Linq allows you to query the data in a dataset.  For this example I load the Products and Categories table from the Northwind Database.  I then do a join query to export the Product Name, Unit Price, and Category Name into a list which I display in a datagridview.  Note a query of this type will not display in a datagridview you need to set the datasource equal to the query's Tolist method.

Imports System.Data.SqlClient

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim strConn As String = _
                "Server = .\SQLEXPRESS;Database = NorthWind; Integrated Security = SSPI;"
        Dim conn As New SqlConnection(strConn)
        Dim da As New SqlDataAdapter("Select * from Products; Select * from Categories", conn)
        Dim ds As New DataSet
        da.Fill(ds)
        Debug.Print(ds.Tables(1).TableName)
        Dim products As DataTable = ds.Tables(0)
        Dim categories As DataTable = ds.Tables(1)
        Dim query = From p In products.AsEnumerable _
                    Join c In categories.AsEnumerable _
                    On p.Field(Of Int32)("CategoryID") Equals c.Field(Of Int32)("CategoryID") _
                    Select New With {.ProductName = p.Field(Of String)("ProductName"), _
                                    .Price = p.Field(Of Decimal)("UnitPrice"), _
                                    .Category = c.Field(Of String)("CategoryName")}

        DataGridView1.DataSource = query.ToList
    End Sub
End Class

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Linq | VB | VS 2008
Posted by Ken Tucker on Thursday, November 08, 2007 11:05 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Paging a Windows Forms DataGridView with LINQ

Since Visual Studio 2008 is due out by the end of the Month I am updating some of my datagridview samples for LINQ.

To start off create a new windows forms application in VS 2008 make sure you select FrameWork 3.5 so you can use linq

 

 

 

I now added a new Linq to Sql designer to the project and named it Northwind.  Drag the Northwind Products Table on to the design surface from the Server Explorer.

 

 

 

 

 

On your windows forms add a DataGridView (DataGridView1) and a NumericUpDown control (nuPage).  For this example I will have the datagridview show 15 items at a time.  In the form load event we will figure out how many pages there are and load the first 15 items into the datagridview.  In the NumericUpdown controls value changed event we will update the data displayed

 

Public Class Form1
    Dim bs As New BindingSource

    Private intPages As Integer
    Dim db As New NorthwindDataContext

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        intPages = Math.Ceiling(db.Products.Count / 15)
        nuPage.Maximum = intPages
        nuPage.Minimum = 1
        Dim p = From prod In db.Products _
                Select prod Skip 0 Take 15
        bs.DataSource = p
        bs.AllowNew = False
        DataGridView1.DataSource = bs
    End Sub


    Private Sub nuPage_ValueChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles nuPage.ValueChanged
        Dim p = From prod In db.Products _
                Select prod Skip (nuPage.Value - 1) * 15 Take 15
        bs.DataSource = p
    End Sub
End Class

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | Linq | VS 2008
Posted by Ken Tucker on Tuesday, November 06, 2007 2:43 AM
Permalink | Comments (0) | Post RSSRSS comment feed

Using Linq for Master Detail in a DataGridView

Using Linq for Master Detail in a DataGridView


I saw in the MSDN forums someone asking how to do a master details relationship with Linq. It is actually pretty simple. Here are the steps involved on creating the relationship. I am using VS 2008 Beta 2 for this example.

  1. Open up Visual Studio 2008 Beta 2 and create a windows forms Application

  2. Add a new Linq 2 Sql classes to the project named Northwind.dbml

  3. Drag the Northwind database's Orders and Order Details table onto the surface

  4. Save the project and build it

  5. Open the data sources window and add a new object data source. Select the orders table

  6. Drag the orders table on your windows form

  7. Drag the orders_details table on the form

  8. In the form load event add this code



VB

Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

Dim db As New NorthwindDataContext

OrderBindingSource.DataSource = From o In db.Orders Select o

End Sub

C#

private void Form1_Load(object sender, EventArgs e)

{

NorthwindDataContext db = new NorthwindDataContext();

orderBindingSource.DataSource = from o in db.Orders select o;

}


Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: DataGridView | Linq
Posted by Ken Tucker on Saturday, August 18, 2007 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed

Using XLinq to get a list of Photos from Spaces.Live.com

Using XLinq to get a list of Photos from Spaces.Live.com


Storing photo albums on line is becoming very popular. Spaces.Live.com photo is one place to store albums which exposes its photo albums via an rss feed. I thought it would be nice to test out Visual Studio 2008 XLinq by getting a list of Photo's from the Tampa Code Camp and display them in WPF Listbox.


The photos I am looking for can be found here.

http://thedevfish.spaces.live.com/photos/cns!75364D9E73295107!133/feed.rss

The xml in the rss feed exposes each photo like this

    <item>
      <title>volunteers arrived at 630am - nikita polyakov [mvp] led them</title>
      <link>http://thedevfish.spaces.live.com/photos/cns!75364D9E73295107!133/cns!75364D9E73295107!134</link>
      <description><p><a href="http://thedevfish.spaces.live.com&#47;photos&#47;cns&#33;75364D9E73295107&#33;133&#47;cns&#33;75364D9E73295107&#33;134" mce_href="http://thedevfish.spaces.live.com&#47;photos&#47;cns&#33;75364D9E73295107&#33;133&#47;cns&#33;75364D9E73295107&#33;134"><img src="http://storage.live.com&#47;items&#47;75364D9E73295107&#33;134&#58;thumbnail" mce_src="http://storage.live.com&#47;items&#47;75364D9E73295107&#33;134&#58;thumbnail" border="0"></a></p><p>volunteers arrived at 630am - nikita polyakov &#91;mvp&#93; led them</p><img src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=8446023494112203015&page=RSS%3a+volunteers+arrived+at+630am+-+nikita+polyakov+%5bmvp%5d+led+them&referrer=" mce_src="http://c.services.spaces.live.com/CollectionWebService/c.gif?cid=8446023494112203015&page=RSS%3a+volunteers+arrived+at+630am+-+nikita+polyakov+%5bmvp%5d+led+them&referrer=" width="1px" height="1px" border="0" alt=""><img style="position:absolute" alt="" width="0px" height="0px" src="http://c.live.com/c.gif?NC=31263&amp;NA=1149&amp;PI=73329&amp;RF=&amp;DI=3919&amp;PS=85545&amp;TP=thedevfish.spaces.live.com&amp;GT1=thedevfish" mce_src="http://c.live.com/c.gif?NC=31263&amp;NA=1149&amp;PI=73329&amp;RF=&amp;DI=3919&amp;PS=85545&amp;TP=thedevfish.spaces.live.com&amp;GT1=thedevfish"></description>
      <comments>http://thedevfish.spaces.live.com/photos/cns!75364D9E73295107!133/</comments>
      <guid isPermaLink="false">cns!75364D9E73295107!134</guid>
      <pubDate>Tue, 24 Jul 2007 18:24:10 GMT</pubDate>
      <slash:comments>0</slash:comments>
      <msn:type>photo</msn:type>
      <live:type>photo</live:type>
      <live:typelabel>Photo</live:typelabel>
      <wfw:commentRss>http://thedevfish.spaces.live.com/photos/cns!75364D9E73295107!133/cns!75364D9E73295107!134/feed.rss</wfw:commentRss>
      <wfw:comment>http://thedevfish.spaces.live.com/photos/cns!75364D9E73295107!133/cns!75364D9E73295107!134</wfw:comment>
      <dcterms:modified>2007-07-24T18:24:10Z</dcterms:modified>
      <enclosure type="image/jpeg" url="http://storage.live.com/items/75364D9E73295107!134" />
    </item>


Lets query the xml feed and get the title for the photo and convert the quid to a link for the photo. The link is http://storage.live.com/items/PictureId. The guid gives us cns!pictureId so we need to replace cns! with http://storage.live.com/items/



Class Window1

    Private Sub Window1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated
        Dim strUrl As String = "http://thedevfish.spaces.live.com/photos/cns!75364D9E73295107!133/feed.rss "
        Dim feeds = XElement.Load(strUrl)

        Dim query = From p In feeds.Element("channel").Elements("item") _
                  Select title = p.Element("title").Value, link = p.Element("guid").Value.ToString.Replace("cns!", "http://storage.live.com/items/")

        lstPhotos.ItemsSource = query.ToList
    End Sub
End Class

Pages 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:CodeCampPhotos"
    Title="Window1" Height="300" Width="300">
    <Grid>
<DockPanel>
<ListBox Name="lstPhotos" DockPanel.Dock="Top">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Path=title}" FontSize="10" />
<Image Source="{Binding Path = link}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
</Grid>
</Window>

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Categories: Asp | Linq
Posted by Ken Tucker on Thursday, August 09, 2007 10:12 PM
Permalink | Comments (0) | Post RSSRSS comment feed