0

我有一个带有按钮和 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 中获得学校名称的长度,列标题为“长度”。

结果

如果我只是在 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
4

3 回答 3

2

试试这个:

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 的属性的匿名对象。DataGridView 通过枚举公共属性并将它们呈现为列来处理这种类型的对象。如果您需要多个值,您可以在花括号内添加其他项目,方法相同,用逗号分隔。有关详细信息,请参阅匿名类型 (Visual Basic)

于 2012-08-02T18:01:14.850 回答
0

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

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

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

于 2012-08-02T14:05:23.597 回答
0

当然,事实证明,这已经经常解决,包括在 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 集合或类似的集合时才可用,并且我的黑客攻击并没有揭示如何做到这一点。)

于 2012-08-02T17:38:37.767 回答