在tabcontrol中跨多个选项卡使用一个datagridview

时间:2013-12-18 16:37:36

标签: vb.net excel datagridview tabcontrol

我在TabControl1的TabPage1上有一个datagridview(datagridview1),这是我的'Records'表单。目前,我使用在页面加载事件上执行的循环填充datagridview,并从excel文件加载数据,它是一个包含的资源。在循环中,我还为excel文件具有的每个工作表和工作表名称创建并命名了选项卡。我在excel文件当前的两张表是名称“2012”和“2013”​​。 TabControl中的第一个选项卡被命名为“2013”​​,第二个选项卡被动态创建并命名为“2012”,因为我通过将当前年份表设置为第一个选项卡来启动循环,并且2013表中的数据通过以下方式读入数据网格视图我的循环。我需要帮助的是在每个新选项卡上使用相同的datagridview,但更新它以显示相应的年份(工作表)数据。

这是我的记录表格代码

Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel

Public Class Records

Dim excel_app As Excel.Application
Dim workbook As Excel.Workbook
Dim sheet_name As String
Dim sheet As Excel.Worksheet
Dim ColumnCount, RowCount, TotalCellCount As Long
Dim yearstamp As String = _
    DateTime.Now.ToString("yyyy")
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")

Sub PopulateDataGridView()
    'Loop through each column
    Dim cIndex As Integer = 0
    Dim rIndex As Integer = 0
    While cIndex < DataGridView1.ColumnCount

        'Loop through and populate each row in column
        rIndex = 0
        While rIndex < DataGridView1.RowCount

            If cIndex = 0 Then
                'Set row header titles
                DataGridView1.Rows.Item(rIndex).HeaderCell.Value = sheet.Range("A1").Offset(rIndex + 1, cIndex).Value()

                DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
            End If
            If cIndex > 0 Then
                DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
            End If

            'Set column header title
            DataGridView1.Columns(cIndex).HeaderText = sheet.Range("A1").Offset(0, cIndex + 1).Value

            'Change last cell (Result) color Red or Green to represent positive gain or negative loss
            If rIndex = RowCount - 2 Then
                If DataGridView1.Rows(rIndex).Cells(cIndex).Value < 0 Then
                    DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Red
                    DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
                End If
                If DataGridView1.Rows(rIndex).Cells(cIndex).Value > 0 Then
                    DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Green
                    DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
                End If
                If DataGridView1.Rows(rIndex).Cells(cIndex).Value = 0 Then
                    DataGridView1.Rows(rIndex).Cells(cIndex).Value = "Broke Even"
                End If

            End If

            rIndex = rIndex + 1

        End While

        'Make column unsortable
        DataGridView1.Columns(cIndex).SortMode = DataGridViewColumnSortMode.NotSortable


        cIndex = cIndex + 1

    End While
End Sub

Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Get the Excel application object.
    excel_app = New Excel.Application

    ' Make Excel visible (optional).
    excel_app.Visible = False

    ' Open the workbook.
    workbook = excel_app.Workbooks.Open(xlPath)

    sheet_name = yearstamp


    'Adds tabs (if needed) and names each tab after respective excel file sheet
    Dim name As String
    For w As Integer = 1 To workbook.Sheets.Count
        name = workbook.Sheets(w).name
        If Not (TabControl1.TabPages.Count = workbook.Sheets.Count) Then
            TabPage1.Text = sheet_name
            ' Create the new tab page
            Dim tab As New TabPage(name)
            ' Add the tabpage to the existing TabCrontrol
            TabControl1.TabPages.Add(tab)
        End If

    Next w


    sheet = excel_app.Worksheets(sheet_name)

    ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
    RowCount = sheet.Range("A1").CurrentRegion.Rows.Count

    DataGridView1.ColumnCount = ColumnCount - 1
    DataGridView1.RowCount = RowCount - 1
    DataGridView1.ColumnHeadersVisible = True
    DataGridView1.RowHeadersVisible = True
    TotalCellCount = DataGridView1.ColumnCount * DataGridView1.RowCount

    DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
    DataGridView1.AllowUserToResizeColumns = False
    DataGridView1.AllowUserToResizeRows = False
    DataGridView1.ReadOnly = True

    DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

    'Calls Loop to populate the datagridview
    PopulateDataGridView()

    DataGridView1.AutoResizeColumns()

    'Resize all Row Headers so user can see Row Titles without resizing
    DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)

End Sub

Private Sub dataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
    If e.ColumnIndex > -1 And e.RowIndex > -1 Then

        If DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = " $0.00" Then
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor = Color.White
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor = SystemColors.Highlight
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor
        End If

    End If



End Sub

我正在编辑此内容,只是为了附加解决方案以防其他人需要一些指导。下面的代码允许我的datagridview被传送到任何激活的选项卡,并且还更新datagridview单元格以显示来自相应excel表格的值的数据。我希望能够提供帮助!

Imports System.Data.OleDb
Imports Microsoft.Office.Interop.Excel

Public Class Records

Dim excel_app As Excel.Application
Dim workbook As Excel.Workbook
Dim sheet_name As String
Dim sheet As Excel.Worksheet
Dim ColumnCount, RowCount, TotalCellCount As Long
Dim yearstamp As String = _
    DateTime.Now.ToString("yyyy")
Dim exeDir As New IO.FileInfo(Reflection.Assembly.GetExecutingAssembly.FullName)
Dim xlPath = IO.Path.Combine(exeDir.DirectoryName, "Records.xlsx")

Sub PopulateDataGridView()
    'Loop through each column
    Dim cIndex As Integer = 0
    Dim rIndex As Integer = 0
    While cIndex < DataGridView1.ColumnCount

        'Loop through and populate each row in column
        rIndex = 0
        While rIndex < DataGridView1.RowCount

            If cIndex = 0 Then
                'Set row header titles
                DataGridView1.Rows.Item(rIndex).HeaderCell.Value = sheet.Range("A1").Offset(rIndex + 1, cIndex).Value()

                DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
            End If
            If cIndex > 0 Then
                DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex + 1, cIndex + 1).Value()
            End If

            'Set column header title
            DataGridView1.Columns(cIndex).HeaderText = sheet.Range("A1").Offset(0, cIndex + 1).Value

            'Change last cell (Result) color Red or Green to represent positive gain or negative loss
            If rIndex = RowCount - 2 Then
                If DataGridView1.Rows(rIndex).Cells(cIndex).Value < 0 Then
                    DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Red
                    DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
                End If
                If DataGridView1.Rows(rIndex).Cells(cIndex).Value > 0 Then
                    DataGridView1.Item(cIndex, rIndex).Style.BackColor = Color.Green
                    DataGridView1.Item(cIndex, rIndex).Style.ForeColor = Color.White
                End If
                If DataGridView1.Rows(rIndex).Cells(cIndex).Value = 0 Then
                    DataGridView1.Rows(rIndex).Cells(cIndex).Value = "Broke Even"
                End If

            End If

            rIndex = rIndex + 1

        End While

        'Make column unsortable
        DataGridView1.Columns(cIndex).SortMode = DataGridViewColumnSortMode.NotSortable


        cIndex = cIndex + 1

    End While
End Sub

Private Sub Records_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    ' Get the Excel application object.
    excel_app = New Excel.Application

    ' Make Excel visible (optional).
    excel_app.Visible = False

    ' Open the workbook.
    workbook = excel_app.Workbooks.Open(xlPath)

    sheet_name = yearstamp


    'Adds tabs (if needed) and names each tab after respective excel file sheet
    Dim name As String
    For w As Integer = 1 To workbook.Sheets.Count
        name = workbook.Sheets(w).name
        If Not (TabControl1.TabPages.Count = workbook.Sheets.Count) Then
            TabPage1.Text = sheet_name
            ' Create the new tab page
            Dim tab As New TabPage(name)
            ' Add the tabpage to the existing TabCrontrol
            TabControl1.TabPages.Add(tab)
        End If

    Next w


    sheet = excel_app.Worksheets(sheet_name)

    ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
    RowCount = sheet.Range("A1").CurrentRegion.Rows.Count

    DataGridView1.ColumnCount = ColumnCount - 1
    DataGridView1.RowCount = RowCount - 1
    DataGridView1.ColumnHeadersVisible = True
    DataGridView1.RowHeadersVisible = True
    TotalCellCount = DataGridView1.ColumnCount * DataGridView1.RowCount

    DataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.DisableResizing
    DataGridView1.AllowUserToResizeColumns = False
    DataGridView1.AllowUserToResizeRows = False
    DataGridView1.ReadOnly = True

    DataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells

    'Calls Loop to populate the datagridview
    PopulateDataGridView()

    DataGridView1.AutoResizeColumns()

    'Resize all Row Headers so user can see Row Titles without resizing
    DataGridView1.AutoResizeRowHeadersWidth(DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders)

End Sub

Private Sub dataGridView1_CellPainting(ByVal sender As System.Object, ByVal e As DataGridViewCellPaintingEventArgs) Handles DataGridView1.CellPainting
    If e.ColumnIndex > -1 And e.RowIndex > -1 Then

        If DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value = " $0.00" Then
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor = Color.White
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.BackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.ForeColor
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor = SystemColors.Highlight
            DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionBackColor = DataGridView1.Item(e.ColumnIndex, e.RowIndex).Style.SelectionForeColor
        End If

    End If

End Sub

Private Sub TabControl1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
    Dim tab As TabPage = Me.TabControl1.SelectedTab
    If ((Not tab Is Nothing) AndAlso (Not tab.Controls.Contains(Me.DataGridView1))) Then
        tab.Controls.Add(Me.DataGridView1)
    End If
    sheet_name = TabControl1.SelectedTab.Text
    sheet = excel_app.Worksheets(sheet_name)
    PopulateDataGridView()
End Sub

1 个答案:

答案 0 :(得分:2)

您可以将DataGridView移动到选定的TabPage:

Private Sub TabControl1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles TabControl1.SelectedIndexChanged
    Dim tab As TabPage = Me.TabControl1.SelectedTab
    If ((Not tab Is Nothing) AndAlso (Not tab.Controls.Contains(Me.DataGridView1))) Then
        tab.Controls.Add(Me.DataGridView1)
        If (Me.isDataLoaded) Then
            'TODO: Me.DataGridView1.DataSource = ?
        End If
    End If
End Sub

Private isDataLoaded As Boolean = False