2016-10-10 54 views
0

我需要datagrid中的多列组合框,从我的数据库显示2个表值,在组合框中用行分隔。我已经用Enter和Draw_Item事件的普通组合框完成了这个工作,现在我正在尝试在DataGrid中执行此操作 - 在Cell_Enter和Cell_Painting事件中。当我尝试设置DataViewrow时出现问题 - 我收到错误“索引不是DatagridView的成员...”。这里是我的代码: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 

任何帮助非常感谢!

回答

0

检查出DataGridViewCellPaintingEventArgs Class的成员。我会尝试利用rowIndex属性:

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

那么你可能需要通过引用单元格属性来获取你所需要的值:

Dim id As String = drv.Cells("Field1").Value.ToString() 
Dim name As String = drv.Cells("Field2").Value.ToString() 
+0

在这里发帖之前,我确实尝试这样做。它不起作用 - “DataGridViewRow类型的值无法转换为DataRowView”错误。 – LuckyLuke82

+0

我已更新以反映这一点,谢谢。 – N0Alias

+0

@没有别名,现在我得到错误:“必须是非负数,并且小于集合的大小”。我在添加组合框之前发生DatagridViewCellPaintingEventArgs。我可以改变这个吗?...我尝试将Cell_Enter代码更改为Form_Load,但仍然是相同的。 – LuckyLuke82