LINQ to SQL datagridview查询返回长度,而不是值

时间:2012-08-02 00:36:58

标签: sql-server-2008 linq-to-sql datagridview vb.net-2010 bindingsource

我有一个带有按钮和datagridview的Windows窗体。该项目包括一个工作数据库连接和LINQ to SQL类。我正在尝试将datagridview绑定到LINQ to SQL。

在代码模块中我得到了这个:

Public Function DataGridList() As BindingSource
    Dim NewBindingSource As New BindingSource()
    Dim db As New DataClasses1DataContext()
    NewBindingSource.DataSource = _
    From Block In db.BLOCK_ASSIGNMENTs
        Where Block.gr912_school = "Franklin"
    Select Block.gr6_school Distinct
    Return NewBindingSource
End Function

这个button_click代码格式为:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    DataGridView1.DataSource = DataGridList()
End Sub

当我点击按钮时,我会在datagridview中获得学校名称的长度,列标题为“length”。

results

如果我只是在button_click中运行这个非常相似的代码,学校名称会在即时窗口中正确显示:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim db As New DataClasses1DataContext()
    Dim TestQuery =
    From Block In db.BLOCK_ASSIGNMENTs
        Where Block.gr912_school = "Franklin"
    Select Block.gr6_school Distinct
    For Each block In TestQuery
        Debug.Print(block)
    Next

End Sub

3 个答案:

答案 0 :(得分:1)

尝试一下:

Public Function DataGridList() As BindingSource
    Dim NewBindingSource As New BindingSource()
    Dim db As New DataClasses1DataContext()
    NewBindingSource.DataSource = _
    From Block In db.BLOCK_ASSIGNMENTs
        Where Block.gr912_school = "Franklin"
    Select New With { Key .Value = Block.gr6_school } Distinct
    Return NewBindingSource
End Function

这应该为它提供DataGridView可以接收的属性。 New With ...使用名为Value的Property创建一个匿名对象。 DataGridView通过枚举公共属性并将它们呈现为列来处理此类对象。如果您需要多个值,则可以使用逗号分隔的相同方式在花括号内添加其他项。有关详细信息,请参阅Anonymous Types (Visual Basic)

答案 1 :(得分:0)

您可以尝试将.ToString添加到Select:

   From Block In db.BLOCK_ASSIGNMENTs
        Where Block.gr912_school = "Franklin"
   Select Block.gr6_school.ToString Distinct

我相信Debug.Print在打印到即时窗口时会对.ToString进行隐式转换。但是,datagrid单元格将所有内容视为对象,并显示该对象的默认属性。

答案 2 :(得分:0)

事实证明,这经常得到解决,包括on SOhere。我选择的路线是使用中间数据表:

Public Function DataGridList() As DataTable
    Dim NewDataTable As New DataTable
    Dim db As New DataClasses1DataContext()
    Dim i As Int32

    Dim qry =
    From Block In db.BLOCK_ASSIGNMENTs.AsEnumerable
        Where Block.gr912_school = "Franklin"
    Select Block.gr6_school Distinct

    NewDataTable.Columns.Add("School")
    For i = 0 To qry.Count - 1
        NewDataTable.Rows.Add(qry(i))
    Next
    Return NewDataTable
End Function

第一次运行时看起来很慢,所以我可能会在将来尝试其他的东西,但它允许我通过LINQ提供网格,这是我想要使用的。

(我想使用qry的CopyToDataTable属性,但只有在查询返回DataTableRows集合或其他类似的情况下它才可用,而我的黑客攻击并未透露如何执行此操作。)