如何使用实体框架和linq创建组合框到dgv

时间:2014-03-16 15:08:01

标签: vb.net linq entity-framework datagridview

我有一个实体框架模型,我绑定到DGV

Dim a as New Model
dim b = from Entry in a.Entries
where Entry.person.windowsusername = SystemInformation.Username.Tostring
Select Entry.Date,
Entry.Begin,
Entry.End,
Entry.Projekt.Projekt_Name

DatagridView1.Datasource = b.tolist

Projekt_Name来自另一个表,我想让用户选择项目。我需要一个组合框,但不知道如何在上面的代码中实现它。我知道如何将linq查询结果绑定到组合框,因为您可以找到它作为msdn示例但无法找到上述问题的vb示例。

1 个答案:

答案 0 :(得分:0)

这不是确切的代码,但应该给你一个想法。 我的代码是将一个组合添加到DataGridView并获取所选项目。它需要你做一些改变。

    Private m_ObjectTemplateColumnAdded As Boolean = False

'Add the combo to the grid
    Private Sub AddObjectTemplateColumn()
        If m_ObjectTemplateColumnAdded Then Exit Sub
        Dim comboBoxColumn As New DataGridViewComboBoxColumn()
        comboBoxColumn.Name = "Combo box column name"
        comboBoxColumn.DisplayMember = "Name"
        comboBoxColumn.DataSource = ' Add you combo source here !!!!
        comboBoxColumn.Width = 150
        DatagridView1.Columns.Add(comboBoxColumn)
        m_ObjectTemplateColumnAdded = True
    End Sub

'ignore grid errors
    Private Sub DatagridView1_DataError(sender As Object, e As DataGridViewDataErrorEventArgs) Handles DatagridView1.DataError
        e.ThrowException = False
    End Sub

'hook to the combo
    Private Sub DatagridView1_EditingControlShowing(ByVal sender As Object, ByVal e As DataGridViewEditingControlShowingEventArgs) Handles DatagridView1.EditingControlShowing

        Dim combo As ComboBox = TryCast(e.Control, ComboBox)
        If (combo IsNot Nothing) Then

            ' Remove an existing event-handler, if present, to avoid  
            ' adding multiple handlers when the editing control is reused. 
            RemoveHandler combo.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)

            ' Add the event handler.  
            AddHandler combo.SelectedIndexChanged, New EventHandler(AddressOf ComboBox_SelectedIndexChanged)

        End If

    End Sub

' Get the selected item from the combo
    Private Sub ComboBox_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
        Dim selectedItem As Object =CType(sender, ComboBox).SelectedItem
        If selectedItemIs Nothing Then Exit Sub
        'do some thing with selectedItem
    End Sub