假设我有一个带有ComboBoxColumn的DataGridView。我按如下方式为ComboBox添加Items:
Dim colors = New Dictionary(Of String, String)()
colors("10") = "Red"
colors("20") = "Blue"
colors("30") = "Green"
colors("40") = "Yellow"
ComboBox1.DataSource = New BindingSource(colors, Nothing)
ComboBox1.DisplayMember = "Value"
ComboBox1.ValueMember = "Key"
然后当程序strarts时,必须从DataBase填充DataGridView,并且ComboBoxes应根据DataBase显示相应的选定项。
在DataBase中,值将 10 , 20 , 30 , 40 ,并且组合框应显示红色,蓝色,绿色,黄色
问题:我如何能够充分利用DATAGRIDVIEW,因为每个COMBOBOX CELL都具有相应的价值?
答案 0 :(得分:1)
这是一个模拟的示例,我模拟数据以模拟从数据库加载。当用户选择项目时,有一个标签显示已更改项目的ValueMember,以便您可以根据需要对其执行某些操作。希望这是有意义的。
''' <summary>
''' There are two columns in the DataGridView, both
''' have the DataProperty set to ParentId for the
''' first column a ComboBox, ChildName for the
''' second column a text box.
''' </summary>
Public Class Form1
WithEvents bsData1 As New BindingSource
WithEvents bsData2 As New BindingSource
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DataGridView1.AutoGenerateColumns = False
bsData2.DataSource = GetParentTable()
Column1.DisplayMember = "ParentName"
Column1.ValueMember = "ParentID"
Column1.DataSource = bsData2
Column1.DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing
bsData1.DataSource = GetChildTable()
DataGridView1.DataSource = bsData1
UpdateLabel()
End Sub
''' <summary>
''' Mocked data, in an app would come from a database table
''' </summary>
''' <returns></returns>
Private Function GetParentTable() As DataTable
Dim dt As New DataTable
With dt.Columns
.Add("ParentID", GetType(Integer))
.Add("ParentName", GetType(String))
End With
With dt.Rows
.Add(10, "Red")
.Add(20, "Blue")
.Add(30, "Green")
End With
dt.AcceptChanges()
Return dt
End Function
''' <summary>
''' Mocked data, in an app would come from a database table
''' </summary>
''' <returns></returns>
Private Function GetChildTable() As DataTable
Dim dt As New DataTable
With dt.Columns
.Add("ChildID", GetType(Integer))
.Add("ParentID", GetType(Integer))
.Add("ChildName", GetType(String))
End With
With dt.Rows
.Add(1, 30, "Child 1")
.Add(2, 20, "Child 2")
.Add(3, 10, "Child 3")
End With
dt.AcceptChanges()
Return dt
End Function
Private Sub DataGridView1_CellEndEdit(
sender As Object,
e As DataGridViewCellEventArgs) Handles DataGridView1.CellEndEdit
UpdateLabel()
End Sub
Private Sub bsData1_PositionChanged(sender As Object, e As EventArgs) Handles bsData1.PositionChanged
UpdateLabel()
End Sub
Private Sub UpdateLabel()
If bsData1.DataSource IsNot Nothing Then
If bsData1.Current IsNot Nothing Then
Label1.Text = CType(bsData1.Current, DataRowView).Row.Field(Of Integer)("ParentID").ToString
End If
End If
End Sub
End Class