שתף באמצעות


Create DataGridView at run time

Question

Thursday, January 31, 2013 3:10 PM

Hi,

Looking for a way to add a DataGridView to a form at run time using vb.net 2008 express and then rename, add new columns and rename each column.

Could some possible provide some code in vb.net which I can then edit to my requirements..

Richard

All replies (4)

Thursday, January 31, 2013 4:38 PM ✅Answered | 1 vote

Hi

Here is an example of creating DGV. This was done in VB 2010 Express, but should be OK in VB 2008 Express.

You need 2 Default Blank Forms. Replace each Form code with the code blocks below.

Public Class Form1
    ' needs a new blank default form1, with this code replacing default code
    Dim butt As New Button
    Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        butt.Text = "Open New Form"
        butt.Location = New Point(30, 20)
        Me.Controls.Add(butt)
        AddHandler butt.Click, AddressOf Button1_Click
    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Dim nf As New Form2
        nf.Show()
    End Sub
End Class
Public Class Form2
    ' needs a new blank default form2, with this code replacing default code

    Private DGV As New DataGridView ' declare a new DataGridView
    Private SplitContainer1 As New SplitContainer ' declare a new SplitContainer
    Private button1, button2 As New Button ' declare 2 new Buttons

    Private Sub Form2_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Me.Width = 600
        ' set up SplitContainer
        SplitContainer1.SplitterDistance = 130
        SplitContainer1.Orientation = Orientation.Vertical
        SplitContainer1.IsSplitterFixed = True
        SplitContainer1.Dock = DockStyle.Fill

        ' add SplitContainer to form
        Me.Controls.Add(SplitContainer1)

        ' add buttons to SplitContainer
        button1.Text = "Find"
        button1.Location = New Point(20, 20)

        button2.Text = "Close"
        button2.Location = New Point(20, 50)

        ' add buttons to SplitContainer Panel2
        Me.SplitContainer1.Panel2.Controls.AddRange({button1, button2})

        ' add handlers for button(s) click
        AddHandler button1.Click, AddressOf Button1_Click
        AddHandler button2.Click, AddressOf Button2_Click

        ' DGV, create 4 columns
        Dim Col1, Col2, Col3, Col4 As New DataGridViewTextBoxColumn

        ' add columns to grid
        DGV.Columns.AddRange(Col1, Col2, Col3, Col4)

        ' set last column to occupy remaining 'space' on grid
        DGV.Columns(3).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

        ' set grid to occupy all of form
        DGV.Dock = DockStyle.Fill

        ' set column titles
        Col1.Name = "ID"
        Col2.Name = "Param1"
        Col3.Name = "Param2"
        Col4.Name = "Other Data"

        ' add grid to SplitContainer Panel1
        Me.SplitContainer1.Panel1.Controls.Add(DGV)

        '  
        ' here, you would populate the DGV or, call a procedure to do it.
        ' this is an example, create dummy test data and add rows to grid
        Dim r As New Random
        For i As Integer = 2 To 18
            DGV.Rows.Add(i, r.Next(9, 21), r.Next(88, 111), "Unknown data")
            Select Case i
                Case 9, 11, 13
                    ' add misc rows for string matching example
                    DGV.Rows.Add(i, r.Next(9, 21), r.Next(88, 111), "Test Data")
                Case 3, 5, 17
                    ' add misc rows for string matching example
                    DGV.Rows.Add(i, r.Next(9, 21), "Test Data2", "Unknown data")
                Case 2, 14, 18
                    ' add misc rows for string matching example
                    DGV.Rows.Add(i, "Test Data3", r.Next(88, 111), "Unknown data")
            End Select
        Next
        '  

    End Sub
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        For Each r As DataGridViewRow In DGV.Rows
            With r
                If Not .IsNewRow Then
                    If .Cells("Other Data").Value.Contains("Test Data") Then
                        .Cells(3).Style.BackColor = Color.Red
                        .Cells(3).Style.ForeColor = Color.Yellow
                    End If

                    If .Cells("Param1").Value.ToString.Contains("Test Data3") Then
                        .Cells(1).Style.BackColor = Color.Blue
                        .Cells(1).Style.ForeColor = Color.White
                    End If

                    If .Cells("Param2").Value.ToString.Contains("Test Data2") Then
                        .Cells(2).Style.BackColor = Color.Green
                        .Cells(2).Style.ForeColor = Color.White
                    End If
                End If
            End With
        Next
    End Sub
    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Me.Dispose()
    End Sub
End Class

Regards Les, Livingston, Scotland


Thursday, January 31, 2013 7:30 PM ✅Answered | 1 vote

Hello,

In addition to Les's code example the following shows working with Checkbox and Link column types. I did not manually create the DataGridView, Les already covered this. Also note how I created the column using With clause which when broken down this way makes things easy to read when (and if) you need to tweak the code down the road.

Public Class Form1    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load        Dim DataRows = _        <Rows>            <Row>                <Action>True</Action>                <Name>VB Forums</Name>                <Link>http://www.vbforums.com/</Link>            </Row>            <Row>                <Action>False</Action>                <Name>Google</Name>                <Link>http://www.google.com</Link>            </Row>            <Row>                <Action>True</Action>                <Name>Social forums</Name>                <Link>http://social.msdn.microsoft.com/</Link>            </Row>            <Row>                <Action>False</Action>                <Name>StackOverflow</Name>                <Link>http://stackoverflow.com/</Link>            </Row>            <Row>                <Action>True</Action>                <Name>Code Project</Name>                <Link>http://www.codeproject.com/</Link>            </Row>        </Rows>        Dim Rows =        (            From x In DataRows...<Row>            Select New With                   {                       .Action = x.<Action>.Value,                       .Name = x.<Name>.Value,                       .Link = x.<Link>.Value                   }        ).ToList        Dim CheckColumn As New DataGridViewCheckBoxColumn With            {                .DataPropertyName = "Action",                .Name = "ActionCol",                .HeaderText = "Action"            }        Dim NameColumn As New DataGridViewTextBoxColumn With            {                .DataPropertyName = "Name",                .Name = "NameCol",                .HeaderText = "Name"            }        Dim LinkColumn As New DataGridViewLinkColumn With            {                .DataPropertyName = "Link",                .Name = "LinkCol",                .HeaderText = "Link"            }        DataGridView1.Columns.AddRange(New DataGridViewColumn() {CheckColumn, NameColumn, LinkColumn})        DataGridView1.DataSource = Rows        DataGridView1.Columns("LinkCol").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill    End Sub    Private Sub DataGridView1_CellContentClick(        ByVal sender As Object,        ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _    Handles DataGridView1.CellContentClick        If TypeOf DataGridView1.Columns(e.ColumnIndex) Is DataGridViewLinkColumn AndAlso Not e.RowIndex = -1 Then            Process.Start(DataGridView1.Item(e.ColumnIndex, e.RowIndex).Value.ToString())        End If    End SubEnd Class

Next example (again DataGridView is already on the form) is for ComboBox column

Public Class Form1    WithEvents bsFileData As New BindingSource    Private dtFileExtensions As New DataTable With {.TableName = "MyExtensions"}    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.Load        Dim dtFiles As New DataTable With {.TableName = "MyFiles"}        With dtFiles.Columns            .AddRange(New DataColumn() _               {                  New DataColumn("Original", GetType(String)),                  New DataColumn("BaseName", GetType(String)),                  New DataColumn("Extension", GetType(String))               }            )        End With        dtFiles.Rows.Add(New Object() {"C:\SomeFile.mdb", Nothing, ".mdb"})        dtFiles.Rows.Add(New Object() {"C:\Data\MyWorkbook.xls", Nothing, ".xls"})        dtFileExtensions.Columns.Add(New DataColumn("Extension", GetType(System.String)))        dtFileExtensions.Rows.Add(New Object() {".mdb"})        dtFileExtensions.Rows.Add(New Object() {".xls"})        bsFileData.DataSource = dtFiles        Dim OriginalName As New DataGridViewTextBoxColumn With         {             .DataPropertyName = "Original",             .HeaderText = "Original",             .Width = 150         }        Dim BaseName As New DataGridViewTextBoxColumn With         {             .DataPropertyName = "BaseName",             .HeaderText = "BaseName",             .DefaultCellStyle = New DataGridViewCellStyle With {.NullValue = "(empty)"},             .Width = 150         }        Dim ExtensionForBaseName As New DataGridViewComboBoxColumn With            {                .DataPropertyName = "Extension",                .DataSource = dtFileExtensions,                .DisplayMember = "Extension",                .DisplayStyle = DataGridViewComboBoxDisplayStyle.Nothing,                .Name = "ExtensionColumn",                .HeaderText = "Extension",                .SortMode = DataGridViewColumnSortMode.Automatic,                .ValueMember = "Extension"            }        DataGridView1.AutoGenerateColumns = False        DataGridView1.Columns.AddRange(New DataGridViewColumn() {OriginalName, BaseName, ExtensionForBaseName})        DataGridView1.DataSource = bsFileData    End SubEnd Class

kevininstructor


Sunday, February 3, 2013 5:01 PM

Hi, bit late getting back to but thanks for the help, Richard


Sunday, February 3, 2013 5:01 PM

Hi, bit late getting back to but thanks for the help, Richard