Datagridview - 多列组合框

时间:2016-10-10 11:27:44

标签: vb.net datagridview

我需要在datagrid中使用多列组合框,以显示来自我的DB的2个表值,在组合框中用线分隔。我已经使用普通的组合框和Enter和Draw_Item事件完成了这项工作,现在我也尝试在datagrid中执行此操作 - 在Cell_Enter和Cell_Painting事件中。当我尝试设置DataViewrow时出现问题 - 我收到错误"索引不是DatagridView的成员......"。这是我的代码:

 Private Sub MyDGV_CellEnter(sender As Object, e As DataGridViewCellEventArgs) Handles MyDGV.CellEnter
        If e.ColumnIndex = 0 Then

            Dim SQL As String = "SELECT Field1,Field2 from MyTable"
            Dim dtb As New DataTable()
            dtb.Columns.Add("Field1", System.Type.GetType("System.String"))
            dtb.Columns.Add("Field2", System.Type.GetType("System.String"))

            Try
               Myconn() 'My connection to Oracle
               Using dad As New OracleDataAdapter(SQL, Myconn)
                    dad.Fill(dtb)
               End Using
               Column1.DisplayMember = "Field1"
               Column1.DataSource = dtb

            Catch ex As Exception
                MessageBox.Show(ex.Message)
            Finally
                Myconn.Close()
            End Try
        End If

 End Sub

    Private Sub MyDGV_CellPainting(sender As Object, e As DataGridViewCellPaintingEventArgs) Handles MyDGV.CellPainting

        If e.ColumnIndex = 0 Then

           Dim drv As DataRowView = CType(Column1.Items(e.Index), DataRowView) 'I have error here - this line should get value of each row   

           Dim id As String = drv("Field1").ToString()
           Dim name As String = drv("Field2").ToString()

           Dim r1 As Rectangle = e.CellBounds
           r1.Width = r1.Width / 2

           Using sb As SolidBrush = New SolidBrush(MyDGV.BackColor)
               e.Graphics.DrawString(id, e.CellStyle.Font, sb, r1)
           End Using

           Using p As Pen = New Pen(Color.AliceBlue)
               e.Graphics.DrawLine(p, r1.Right, 0, r1.Right, r1.Bottom)
           End Using

           Dim r2 As Rectangle = e.CellBounds
           r2.X = e.CellBounds.Width / 2
           r2.Width = r2.Width / 2

           Using sb As SolidBrush = New SolidBrush(MyDGV.BackColor)
               e.Graphics.DrawString(name, e.CellStyle.Font, sb, r2)
           End Using

        End If

    End Sub

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

查看DataGridViewCellPaintingEventArgs Class的成员。我会尝试利用RowIndex属性:

Dim drv As DataGridViewRow = CType(MyDGV.Rows(e.RowIndex), DataGridViewRow)

然后,您可能需要通过引用cells属性来获取所需的值:

Dim id As String = drv.Cells("Field1").Value.ToString()
Dim name As String = drv.Cells("Field2").Value.ToString()
相关问题