Click here to Skip to main content
Licence 
First Posted 30 Aug 2005
Views 91,194
Bookmarked 25 times

DataGrid ColumnStyle as LinkLabel

By | 19 Jul 2006 | Article
To create a column style of a DataGrid as a LinkLabel.

Introduction

I was asked by someone how to create a DataGrid column style as a LinkLabel for a DataGrid. I present below the code for a control for a DataGrid column style made by me. I have made some changes in the code and I am updating this article by submitting the code for the article. Many people asked for the code of this article.

There are many ColumnStyles defined such as DataGridComboColumn, DataGridLabelColumn etc.

Using the Code

Overriding the methods

To create a column style, you need to subclass the abstract DataGridColumnStyle class. Here is the list of the methods that you need to implement:

Protected Overrides Sub Abort(ByVal rowNum As Integer)

The function Abort(ByVal rowNum as Integer) determines how the active column cell is to react to the user's request to interrupt the editing procedure.

Protected Overrides Function Commit (ByVal datasource As _
    CurrencyManager, ByVal  rowNum As Integer) As Boolean

The function Commit() implements a logic that updates the cell with the new value, and prepares the updated data to be pushed back to the property descriptor using the base class SetColumnValueAtRow method.

Protected Overloads Overrides Sub Edit(ByVal source As _
    System.Windows.Forms.CurrencyManager, ByVal rowNum As Integer, ByVal bounds _
    As System.Drawing.Rectangle, ByVal [readOnly] As  Boolean, _
    ByVal instantText  As  String)

Edit allows you to prepare the cell for editing, using the specified System.Windows.Forms.CurrencyManager, row number, and System.Drawing.Rectangle parameters.

Protected Overrides Function GetMinimumHeight() As Integer

GetMinimumHeight() returns the desired minimum height of the cells in the grid.

Protected Overrides Function GetPreferredHeight(ByVal g _
    As Graphics, ByVal value As Object) As Integer

GetPreferredHeight() returns the preferred cell height. When the user double-clicks on a row border, this method is invoked on all of the column styles that reside in the current table style's GridColumnStyleCollection.

Protected Overrides Function GetPreferredSize(ByVal g _
    As Graphics, ByVal value As Object) As System.Drawing.Size

GetPreferredSize() returns the preferred cell size. This method does the same thing as the GetPreferredHeight method, only it is invoked when the user double-clicks on a column border. The column to the left of the border is then set to the width of the returned Size object.

Protected Overloads Overrides Sub Paint(ByVal g As _
    System.Drawing.Graphics, ByVal bounds As System.Drawing.Rectangle, _
    ByVal source As System.Windows.Forms.CurrencyManager, _
    ByVal rowNum As Integer)

In this Paint() method, call the following Paint() method, passing alignToRight value as False.

Protected Overloads Overrides Sub Paint (ByVal g As Graphics, _
    ByVal bounds As Rectangle, ByVal source As CurrencyManager, _
    ByVal rowNum As Integer, ByVal backBrush As Brush, _
    ByVal foreBrush As Brush, ByVal alignToRight As Boolean)

This is the second of the three overloaded (and second of the two abstract) Paint methods in DataGridColumnStyle. This method paints the cells in the column, one cell at a time. You also receive a reference to a CurrencyManager object that represents the binding and contains the data that is to be displayed in the grid. By invoking the DataGridColumnStyle's GetColumnValueAtRow method, you can obtain the value for the current cell.

Creating Custom ColumnStyles

Protected Overloads Overrides Sub Paint(ByVal g As Graphics, _
    ByVal bounds As Rectangle, ByVal source As CurrencyManager, _
    ByVal rowNum As Integer, ByVal backBrush As Brush, _
    ByVal foreBrush As Brush, ByVal alignToRight As Boolean)

    Dim o As Object = Me.GetColumnValueAtRow([source], rowNum)
    Dim linkText As String = Microsoft.VisualBasic.IIf((o Is Nothing _
                    OrElse o Is DBNull.Value), Me.NullText, o.ToString)

    If (links.Contains(rowNum)) Then
    m_link = CType(links(rowNum), LinkLabel)
        If Not (m_link.Bounds.Equals(bounds)) Then
            m_link.Bounds = bounds
            m_link.Visible = True
        End If
    Else
        m_link = New LinkLabel
        m_link.Text = linkText
        m_link.Parent = Me.DataGridTableStyle.DataGrid
        m_link.Links.Add(0, linkText.Length, o)
        m_link.Bounds = bounds
        AddHandler m_link.LinkClicked, AddressOf link_LinkClicked
        links(rowNum) = m_link
    End If
End Sub

Usage: Bind Controls to DataGrid - How to use the column style in your application?

Private Sub BindControls()

    Dim dmTable As New DataTable("Test")
    dmTable.Columns.Add(New DataColumn("SNO", GetType(Integer)))
    dmTable.Columns.Add(New DataColumn("AuthorName", GetType(String)))
    dmTable.Columns.Add(New DataColumn("WebAddress", GetType(String)))

    Dim dr As DataRow = dmTable.NewRow()
    dr("SNO") = 1
    dr("AuthorName") = "Chris"
    dr("WebAddress") = "http://msdn.microsoft.com/smartclient/" & _ 
                       "default.aspx?pull=/library/en-us/" & _ 
                       "dnwinforms/html/datagridcolumnstyle2.asp"
    dmTable.Rows.Add(dr)

    Dim dr2 As DataRow = dmTable.NewRow()
    dr2("SNO") = 2
    dr2("AuthorName") = "Evan"
    dr2("WebAddress") = "http://msdn.microsoft.com/smartclient/default.aspx" & _ 
                        "?pull=/library/en-us/dnwinforms/html/" & _ 
                        "datagridcolumnstyle1.asp"
    dmTable.Rows.Add(dr2)

    Dim dr3 As DataRow = dmTable.NewRow()
    dr3("SNO") = 3
    dr3("AuthorName") = "Chris"
    dr3("WebAddress") = "http://www.micrsoft.com/"
    dmTable.Rows.Add(dr3)

    dataGrid.TableStyles.Add(CreateTableStyle())
    dataGrid.DataSource = dmTable
End Sub 'BindControls

Create Table Style:

Private Function CreateTableStyle() As DataGridTableStyle

    Dim dst As New DataGridTableStyle
    dst.MappingName = "Test"

    Dim cs As New ColumnStyles.ColumnStyles.DataGridLinkLabelColumn
    AddHandler cs.LinkClicked, AddressOf cs_LinkClicked
    cs.MappingName = "WebAddress"
    cs.HeaderText = "Web Address"

    Dim cb As New DataGridTextBoxColumn
    cb.MappingName = "SNO"
    cb.HeaderText = "S No"

    Dim cs2 As New DataGridTextBoxColumn
    cs2.MappingName = "AuthorName"
    cs2.HeaderText = "Author Name"

    dst.GridColumnStyles.Add(cb)
    dst.GridColumnStyles.Add(cs2)
    dst.GridColumnStyles.Add(cs)
    Return dst
End Function  'CreateTableStyle

Adding handler for the LinkClicked event:

Private Sub cs_LinkClicked(ByVal sender As Object, _
                           ByVal e As LinkLabelLinkClickedEventArgs) 
    MessageBox.Show("cs_linkclicked:You have clicked the link") 
End Sub

To Fix It

If the contents of the column are larger (as seen in the figure), then it cannot be viewed properly even if we increase the size of the DataGrid column.

Acknowledgements

Many thanks for giving the idea of how to create a DataGrid column style: Styling with the DataGridColumnStyle, Part 1 by Chris Sano. There is also another article by Chris Sano describing DataGrid column styles for further reading. Many thanks to all of those who have appreciated and are using the DLL in their projects.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Nidhi S

Web Developer

India India

Member

Nidhi Shrivastava
B.Sc (Maths), M.Sc(Maths), PGDCA(NIIT)
Working as a freelance software developer.
 
Experienced in C# .NET, VB .NET, VB 6.0, SQL Server 2000, Java 2 SDK.
 
Worked with PMPCertify (home based) (pmpcertify.org).
Currently working with .NET and its technology for last 1 and half years. Previously worked with VB 6.0 and have done many projects using it.
 
Hobbies include reading, music and travelling.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
QuestionNeed datagrid with first twocolumn no horizontal scroll, kind of fixed. Pinmemberiaminterested14:37 17 Aug '08  
GeneralBinding data from a mysql database Pinmemberdon_omar23:36 14 May '08  
GeneralProblems regarding this article Pinmemberdon_omar22:42 12 May '08  
Generalhelp about links object Pinmemberhasanw0715:46 26 Jul '07  
QuestionRefresh , for new search criteria. Pinmembersameya18:52 8 Jul '07  
AnswerRe: Refresh , for new search criteria. Pinmembermccalla17:33 3 Oct '07  
GeneralRe: Refresh , for new search criteria. Pinmemberriteshbawaskar0:04 27 May '10  
GeneralYour Code PinmemberModernDog23:23 4 Jun '07  
GeneralRe: Your Code Pinmemberdon_omar22:51 12 May '08  
GeneralScrolling Pinmemberjcrussell16:43 24 May '07  
AnswerRe: Scrolling Pinmemberjcrussell16:51 24 May '07  
GeneralRe: Scrolling PinmemberNidhi S1:59 29 May '07  
GeneralBug Fix :) PinmemberTertioptus12:53 12 Apr '07  
GeneralRe: Bug Fix :) PinmemberNidhi S16:44 12 Apr '07  
GeneralProblems Pinmemberjake0724:46 23 Jan '07  
GeneralLinks don't change when the datagrid source changes Pinmembersean1232311234:46 16 Nov '06  
GeneralExcellent Article Pinmemberjaguar57466:22 8 Nov '06  
QuestionHow would i get the datagrid row to change to the selected row Pinmemberanwarhamr10:30 7 Sep '06  
GeneralRe: How would i get the datagrid row to change to the selected row Pinmemberanwarhamr12:44 8 Sep '06  
AnswerRe: How would i get the datagrid row to change to the selected row PinmemberElyzzea21:32 19 Mar '07  
Hi!
This may be a late answer but it could help some people Smile | :)
I had the same problem with the Linklabel Columnstyle. I couldn't get the right selected row.
Only the first row was selected, even if I clicked on the linklabel in another line.
I found a solution to finally get the right row. Please, find the code below. I hope this will help.

'*****************************************************
'Code to get the selected row
'Get the mouse position
Dim XX As Integer = MousePosition.X
Dim YY As Integer = MousePosition.Y
 
'Find out which cells (row+column) are clicked with the mouse
Dim p1 As Point = DataGrid1.PointToClient(New Point(XX, YY))
'MessageBox.Show(DataGrid1.HitTest(p1).ToString()) 'test
 
'Find out which line of the datagrid is selected
DataGrid1.CurrentRowIndex = DataGrid1.HitTest(p1).Row
 
'select the line
DataGrid1.IsSelected(DataGrid1.CurrentRowIndex)
 
'Row number
Dim PointCell As DataGridCell
PointCell.RowNumber = DataGrid1.HitTest(p1).Row
'*****************************************************

 
Regards
Elyzzea
Generalwks well Pinmemberanil kornepati21:41 6 Aug '06  
QuestionThe white space Pinmemberfabguy4:12 24 Jul '06  
GeneralRe: The white space PinmemberNidhi S19:22 24 Jul '06  
GeneralRe: The white space Pinmemberfabguy23:52 24 Jul '06  
GeneralRe: The white space Pinmemberfabguy0:44 25 Jul '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 19 Jul 2006
Article Copyright 2005 by Nidhi S
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid