我有一个包含3列的datagridview - Name [string],Width [Integer],Thickness [Integer] . 数据源的宽度和厚度来自外部表id [Integer] . 我想在datagridview中显示实际的文本值而不是ID值 . 我正在使用带有标准填充的数据集(全选) . 我还有两个组合框下拉列表,它们将绑定到datagridview绑定的bindingsource的值 . 如何让厚度和宽度的DataGridView列显示来自WidthBindingSource和ThicknessBindingSource的Name字段的Text Value .

我试图在DataGridView的CellFormatting事件中处理这个,但我无法更改列以在事件args e.Value等中使用格式化值类型的字符串 .

代码发布如下 .

Private Sub dgvDimension_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles dgvDimension.CellFormatting
    Dim dgv As DataGridView = DirectCast(sender, DataGridView)

    Dim IsWidthColumn As Boolean = dgv.Columns(e.ColumnIndex).Name.ToLower() = "width"
    Dim IsThicknessColumn As Boolean = dgv.Columns(e.ColumnIndex).Name.ToLower() = "thickness"

    Dim columnName As String = dgv.Columns(e.ColumnIndex).Name


    If IsWidthColumn OrElse IsThicknessColumn Then

        If dgv.Columns(e.ColumnIndex).Name.ToLower() = columnName AndAlso e.RowIndex >= 0 AndAlso TypeOf dgv(columnName, e.RowIndex).Value Is Integer Then

            Dim dt As DataTable = New DataTable

            Select Case columnName.ToLower()

                Case "width"

                    dt = DirectCast(WidthBindingSource1.DataSource, DataTable)

                    Exit Select

                Case "thickness"

                    dt = DirectCast(ThicknessBindingSource.DataSource, DataTable)

                    Exit Select

                Case Else

            End Select



            Dim expression As String = "Id=" & dgv(columnName, e.RowIndex).Value.ToString()

            Dim dRow As DataRow = dt.Select(expression).FirstOrDefault

            If Not dRow Is Nothing Then


                e.Value = dRow("Name").ToString()

                e.FormattingApplied = True


            End If

        End If


    End If


End Sub

更多代码信息如下 - 表,bindingsource,数据集和查询信息的结构 .

Select ID, Name, Width, Thickness From Dimension [DimensionBindingSource DataSet.Dimension]

[Width and Thickness need to appear in DataGridView as Width.Name and Thickness.Name - I need to be able to update the Dimension table from this form using the DimensionBindingSource. ]

Select ID, Name From Width [WidthBindingSource DataSet.Width]

Select ID, Name From Thickness  [ThicknessBindingSource DataSet.Thickness]


My cmbWidth and cmbThickness SelectedValues are bound to Dimension.Width, Dimension.Thickness