Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataGrid Class 2

Status
Not open for further replies.

SqueakinSweep

Programmer
Jun 20, 2002
945
GB
Having seen many questions about the datagrid, especially relating to column styles. After all every grid you design realistically needs some design touches adding and the MS Datagrid is not the easiest control in the world to work with on this front.

Because of this, and partly as an exercise to myself to figure out a little about Datagrid (I generally use C1 TrueDBGrid), I designed a little grid class, which hopefully other forum users will add to and build on. Eventually we could end up with TekTips Grid...

When I get time and a few revisions I will add this as an FAQ. Please feel free to add suggestions or add to the source.

The control is a component class, inheriting the Datagrid
Code:
Imports System.Drawing

Public Class comDataGrid
    Inherits DataGrid

    Dim sColumns As String
    Dim sMapping As String
    Dim sWidths() As String
    Dim sHeaders() As String
    Dim sAlignments() As String

    Dim ts As New DataGridTableStyle
    Dim rw As DataGridColumnStyle

Public Sub zSetDataSource(ByVal dt As DataTable)

        Me.DataSource = dt
        Me.sMapping = dt.TableName

        'Assign Mapping name to TableStyle
        ts.MappingName = dt.TableName

        'Build a String of all columns.
        For Each c As DataColumn In dt.Columns
            Me.sColumns += c.ColumnName.Trim + ","
        Next
        Me.sColumns = Me.sColumns.TrimEnd(","c)

    End Sub

    Public Sub zSetColumnstoShow(ByVal s As String)
        Me.sColumns = s
    End Sub

    Public Sub zSetColumnWidths(ByVal sColumnWidths As String)
        Me.sWidths = sColumnWidths.Split(","c)
    End Sub

    Public Sub zSetColumnHeaders(ByVal sColumnHeaders As String)
        Me.sHeaders = sColumnHeaders.Split(","c)
    End Sub

    Public Sub zSetColumnAlignMents(ByVal sAlignMents As String)
        Me.sAlignments = sAlignMents.Split(","c)
    End Sub

    Public Sub zBuildGrid()

        Dim dgcol As DataGridTextBoxColumn

        Dim iloop As Integer = 0
        For Each s As String In Me.sColumns.Split(","c)

            'Define and apply the column settings
            dgcol = New DataGridTextBoxColumn
            dgcol.ReadOnly = True
            dgcol.MappingName = s
            'Column Header
            If iloop < Me.sHeaders.Length Then
                dgcol.HeaderText = CStr(Me.sHeaders(iloop))
            End If
            'Column Width
            If iloop < Me.sWidths.Length Then
                dgcol.Width = CInt(Me.sWidths(iloop))
            End If
            'Column AlignMent
            If iloop < Me.sAlignments.Length Then
                Dim sAlign As String = CStr(Me.sAlignments(iloop))
                Select Case sAlign
                    Case "L"
                        dgcol.Alignment = HorizontalAlignment.Left
                    Case "C"
                        dgcol.Alignment = HorizontalAlignment.Center
                    Case "R"
                        dgcol.Alignment = HorizontalAlignment.Right
                End Select
            End If

            'Add to TableStyle
            ts.GridColumnStyles.Add(dgcol)

            iloop += 1

        Next

        With Me
            .TableStyles.Add(ts)
            .TableStyles(Me.sMapping).ReadOnly = True
            .TableStyles(Me.sMapping).AllowSorting = False
        End With

        Me.Select(0)

    End Sub

    Private Sub comDataGrid_MouseUp(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles MyBase.MouseUp

        Dim pt As New Point(e.X, e.Y)

        Dim hti As DataGrid.HitTestInfo = Me.HitTest(pt)
        If hti.Type = DataGrid.HitTestType.Cell Then
            Me.CurrentCell = New DataGridCell(hti.Row, hti.Column)
        End If

    End Sub

    Private Sub comDataGrid_CurrentCellChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles MyBase.CurrentCellChanged

        Me.Select(Me.CurrentCell.RowNumber)

    End Sub

End Class

Usage
Build and add to toolbar, then drop onto a new form
Sample usage code below
Code:
With xGrid
   .zSetDataSource(dt) ' DataTable
   .zSetColumnHeaders("FirstName,LastName,Salary")
   .zSetColumnWidths("100,150,80")
   .zSetColumnAlignMents("L,L,R")
   .zBuildGrid()
End With




Sweep
...if it works dont mess with it
 
Errm...apologies for the mispost on the usage code. I omitted the line which selects which columns to display

Code:
With xGrid
   'Assign the Datatable
   .zSetDataSource(dt)
   'List of Fields that you want to display
   .zSetColumnstoShow("firstname,surname,payment")
   'Comma delim list of Column Headers
   .zSetColumnHeaders("FirstName,LastName,Salary")
   'Comma Delim List of Column Widths
   .zSetColumnWidths("100,150,80")
   'Comma Delim List of Column Alignments
   .zSetColumnAlignMents("L,L,R")
   'Ok...go build the Grid
   .zBuildGrid()
End With


Sweep
...if it works dont mess with it
 
How about an explanation of what it does differently and better, as well as what the goals are for it?
 
I think we should form a commitee and design a flex/data grid that performs in a way that it is flexable enough to meet peoples needs and straight forward enough so that everyone can use it. The C1 Flexgrid (my tool of choice) works well most of them time, but it's not nearly as flexable as I would like, and there are issues w/ threading and color.

-Rick

----------------------

[monkey] I believe in killer coding ninja monkeys.[monkey]
 
Excellent idea. I am struggling to get to grips with this control. Would be very useful to have a step by step instruction as to how to create/install. As VB.Net is new to me, I still cannot get the procedure for inserting lumped code. In VB6, you could just paste in a load of code and it found its way in. VB.Net seems not to be so user friendly to do this - or is it me?.
regards.
 
All the grid class really does is to serve as a wrapper for Table and Column Styles, and provides a very easy mechanism for defining the columns to be displayed in a grid, and the widths, column headers and alignment of those columns.

ZOR...you can cut and paste most of this code. All yo need to do first is to add a component to your project, and tell it to ingherit the datagrid. If you then paste all the code from above and remove the Inherits line, you have the code you need. From that point its just a case of rebuilding and then adding the new grid class to your toolbar.

Im not trying to design a new grid, just to give new .Net users an easy introduction to the Datagrid control, but it certainly has potential to be built upon.



Sweep
...if it works dont mess with it
 
Many thanks Sweep. I would give you another star but I've already submitted mine. Must be many others who appreciate something like this, not very easy move from VB6, nothing makes sense to me at the moment, Bill Gates must have a sense of humour somewhere? Regards
 
Zor
You're welcome, glad to be of some help.

Sweep
...if it works dont mess with it
 
Very cool Sweep.
 
Nice piece of work SqueakinSweep. I implemented it and it works for the columnwidths, alignments etc. etc. But unfortunately I have some problems with settings some other properties. Here is my code

Code:
With gridParties
            .zSetDataSource(dsUsers.Tables(0))
            .zSetColumnHeaders("Id,Bedrijf,Plaats,Contact")
            .zSetColumnWidths("30,100,100,100")
            .zSetColumnAlignMents("L,L,L,L")
            .zBuildGrid()

            .BackColor = System.Drawing.Color.Red
            .AlternatingBackColor = System.Drawing.Color.AliceBlue
            .BackgroundColor = System.Drawing.Color.Bisque
            .RowHeadersVisible = False
            .ParentRowsVisible = False
            .ReadOnly = True                    'no editing allowed in the datagrid
        End With

After building the grid with your class it seems that properties i.e. .rowheadervisible and the .alternatingbackcolor can not be set. It does not work with the code above. What am I doing wrong?

Regards,
 
Without looking too deeply into it, try making zbuildgrid the last thing you do.


Sweep
...if it works dont f*** with it
...if its f****ed blame someone else
...if its your fault that its f***ed, say and admit nothing.
 
Thanks for your reply. Well, putting the zBuildGrid statement as last within the with/end-with was my first guess also, but I does not help.

The strange this is that
.BackgroundColor = System.Drawing.Color.Bisque
is executed but
.ParentRowsVisible = False
is not. Beats me :)
 
As for colors and column/row headers, you will probably have to apply these to the tablestyle, before applying the tablestyle to the grid itself. You could very easily amend the code to pick these settings from the grids current properties.



Sweep
...if it works dont f*** with it
...if its f****ed blame someone else
...if its your fault that its f***ed, say and admit nothing.
 
OK, I see what you mean. I will look into that. Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top