Login or Sign Up to become a member!
LessThanDot Sit Logo

LessThanDot

Community Wiki

Less Than Dot is a community of passionate IT professionals and enthusiasts dedicated to sharing technical knowledge, experience, and assistance. Inside you will find reference materials, interesting technical discussions, and expert tips and commentary. Once you register for an account you will have immediate access to the forums and all past articles and commentaries.

LTD Social Sitings

Lessthandot twitter Lessthandot Linkedin Lessthandot friendfeed Lessthandot facebook Lessthandot rss

Note: Watch for social icons on posts by your favorite authors to follow their postings on these and other social sites.

Navigation

Google Ads

VB.NET: Type extensions

From Wiki

Jump to: navigation, search

One of the best features after LINQ in Visual Studio 2008 is type extensions. Extensions permit developers to take function based code to method base code.

Function base example

  1. Dim ExampleNumber As String = "100"
  2.    Console.WriteLine(Convert.ToInt32(ExampleNumber))

Method base example (uses extensions)

  1. Dim ExampleNumber As String = "100"
  2.    Console.WriteLine(ExampleNumber.ToInteger)


Let's look at the underlying source code which will assist in understanding extensions. An extension begins with the attribute tag of <Extension> from the System.Runtime.CompilerServices namespace. The parameter value is the variable using the extension i.e. ExampleNumber, the variable in the example is value.

  1. <Extension()> _
  2. Public Function ToInteger(ByVal value As String) As Integer
  3.     Return Convert.ToInt32(value)
  4. End Function
  5. <Extension()> _
  6. Public Function ToInteger(ByVal value As Boolean) As Integer
  7.     Return Convert.ToInt32(value)
  8. End Function

To pass a value to the extension a second parameter is required. The first example simple increments a string by one while the second example allows the amount to increment by.

  1. <Extension()> _
  2. Public Function Increment(ByRef value As Int32) As Int32
  3.    Return value + 1
  4. End Function
  5. <Extension()> _
  6. Public Function Increment(ByRef value As Int32, ByVal Amount As Int32) As Int32
  7.    Return value + Amount
  8. End Function

A word of advice, all the examples shown have no exception handling or type checking, this is a decision you need to make up front. If you decide to there are various avenues such as using another extension as shown below.

  1. <Extension()> _
  2. Public Function IsInteger(ByVal value As String) As Boolean
  3.     Return System.Text.RegularExpressions.Regex.IsMatch(value, "^[-+]?\d+$")
  4. End Function

When writing extensions it is best to take time to consider what should be an extension along with taking time to write them properly rather than simply using them because they are a new edition to the language.

Below are some suggestions for everyday use. Some are my creations while others were found on the web copied as found or modified slightly.

  1. <Extension()> _
  2.     Public Function Format(ByVal value As Double) As String
  3.         Return value.ToString("F2")
  4.     End Function
  5.     <Extension()> _
  6.     Public Function Format(ByVal value As Double, ByVal Places As Integer) As String
  7.         Return value.ToString(String.Format("F{0}", Places))
  8.     End Function
  9.     <Extension()> _
  10.     Public Function ToDouble(ByVal value As String) As Double
  11.         Return Convert.ToDouble(value)
  12.     End Function
  13.     <Extension()> _
  14.     Public Function Increment(ByRef value As String) As Int32
  15.         Return value.ToInteger + 1
  16.     End Function
  17.     <Extension()> _
  18.     Public Function Decrement(ByRef value As String) As String
  19.         Return CStr(value.ToInteger - 1)
  20.     End Function
  21.     <Extension()> _
  22.     Public Function Decrement(ByRef value As Int32) As Integer
  23.         Return value - 1
  24.     End Function
  25.     <Extension()> _
  26.      Public Function Increment(ByRef value As Int32) As Int32
  27.         Return value + 1
  28.     End Function
  29.     <Extension()> _
  30.     Public Function RightAlign(ByVal value As String, ByVal Spaces As Int32) As String
  31.         Return String.Format("{0," & Spaces & "}", value)
  32.     End Function
  33.     <Extension()> _
  34.     Public Function LeftAlign(ByVal value As String, ByVal Spaces As Int32) As String
  35.         Return String.Format("{0,-" & Spaces & "}", value)
  36.     End Function
  37.     <Extension()> _
  38.     Function TabStop(ByVal value As String) As String
  39.         Return value & System.Text.RegularExpressions.Regex.Unescape("\t")
  40.     End Function
  41.     <Extension()> _
  42.     Public Function ProperCase(ByVal value As String) As String
  43.         Dim TI As System.Globalization.TextInfo = New System.Globalization.CultureInfo("en-US", False).TextInfo
  44.         Return TI.ToTitleCase(value.ToLower)
  45.     End Function
  46.     <Extension()> _
  47.     Public Function ToDate(ByVal value As String) As Date
  48.         Dim Parts As String() = value.Split(",".ToCharArray)
  49.         Dim Year As Integer = Parts(0).ToInteger
  50.  
  51.         Return New DateTime(Parts(0).ToInteger, Parts(1).ToInteger, Parts(2).ToInteger)
  52.     End Function
  53.     <Extension()> _
  54.     Public Sub PrintToConsole(ByVal dv As DataView, ByVal ColumnName As String)
  55.         For i As Integer = 0 To dv.Count - 1
  56.             Console.WriteLine("".TabStop & dv(i)(ColumnName).ToString())
  57.         Next
  58.     End Sub

I do not use CheckBox columns in DataGridViews very much and when wanting to know if a column is checked or not say in the CellContentClick event I need only point to a simple extension.

  1. <Extension()> _
  2.     Function CurrentRowCheckBoxValue( _
  3.         ByVal GridView As DataGridView, _
  4.         ByVal ColumnName As String) As Boolean
  5.  
  6.         GridView.EndEdit() ' Must be here else you will not get the proper value
  7.  
  8.         Return Convert.ToBoolean( _
  9.             GridView.Rows(GridView.CurrentRow.Index).Cells(ColumnName).Value)
  10.  
  11.     End Function

Example, we have a CheckBox column in a DataGridView named CheckList.

  1. Private Sub DataGridDemo_CellContentClick( _
  2.         ByVal sender As Object, _
  3.         ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) _
  4.         Handles DataGridView1.CellContentClick
  5.  
  6.         Dim GridView As DataGridView = DirectCast(sender, DataGridView)
  7.         If GridView.CurrentRowCheckBoxValue("CheckList") Then
  8.            ' Do something
  9.         End If

Here is an extension which used LINQ to search for text in a specific column in a DataGridView by ColumnName. I have overloaded this to also search by Column Index and close matches but showing one version to keep things in target and simple to understand.

  1. <Runtime.CompilerServices.Extension()> _
  2.     Public Function Seek(ByVal GridView As DataGridView, _
  3.                          ByVal ColumnName As String, ByVal Value As String, _
  4.                          ByVal f As Form) As Boolean
  5.         Dim Located As Boolean = False
  6.         If GridView.Columns.Contains(ColumnName) Then
  7.  
  8.             Dim SingleRow As DataGridViewRow = _
  9.                 (From Rows In GridView.Rows.Cast(Of DataGridViewRow)() _
  10.                  Where Rows.Cells(ColumnName).Value.ToString() = Value).FirstOrDefault
  11.  
  12.             If Not IsNothing(SingleRow) Then
  13.                 If GridView.CurrentCell.RowIndex <> SingleRow.Index Then
  14.                     GridView.CurrentCell = GridView(0, SingleRow.Index)
  15.                 End If
  16.                 Located = True
  17.                 f.ActiveControl = GridView
  18.             End If
  19.             Return Located
  20.         Else
  21.             Throw New Exception("Column '" & ColumnName & _
  22.                                 "' not contained in this DataGridView")
  23.         End If
  24.     End Function

Example usage. The DataGridView has a ID Column where the text is upper cased. If a match to the text in Textbox1 is found we activate the grid and position to the row we found the match on. Note the column is hard coded but with minor changes we could always set the column to match the column name we are searching on. If no match we make the textbox the active control.

  1. Private Sub cmdFind_Click() Handles cmdFind.Click
  2.         If Not DataGridView1.Seek("ID", TextBox1.Text.ToUpper, Me) Then
  3.             ActiveControl = TextBox1
  4.         End If
  5.     End Sub


Consider the following extension, the intent here is to make the code using this code easier to read as we could have created a function or done the code inplace I favored implementing as an extension.

  1. <Runtime.CompilerServices.Extension()> _
  2.     Function RemoveDoubleQuotes(ByVal value As String) As String
  3.         If String.IsNullOrEmpty(value) Then
  4.             Return String.Empty
  5.         End If
  6.         Return System.Text.RegularExpressions.Regex.Replace(value, "[""]", String.Empty)
  7.     End Function
  8.     <Runtime.CompilerServices.Extension()> _
  9.     Function RemoveDoubleQuotes(ByVal value As String, ByVal Replacement As String) As String
  10.         If String.IsNullOrEmpty(value) Then
  11.             Return String.Empty
  12.         End If
  13.         Return System.Text.RegularExpressions.Regex.Replace(value, "[""]", Replacement)
  14.     End Function
  15.     <Runtime.CompilerServices.Extension()> _
  16.     Function RemoveSingleQuotes(ByVal value As String) As String
  17.         If String.IsNullOrEmpty(value) Then
  18.             Return String.Empty
  19.         End If
  20.         Return System.Text.RegularExpressions.Regex.Replace(value, "[']", String.Empty)
  21.     End Function
  22.     <Runtime.CompilerServices.Extension()> _
  23.     Function RemoveSingleQuotes(ByVal value As String, ByVal Replacement As String) As String
  24.         If String.IsNullOrEmpty(value) Then
  25.             Return String.Empty
  26.         End If
  27.         Return System.Text.RegularExpressions.Regex.Replace(value, "[']", Replacement)
  28.     End Function

See Reading SQL from embedded resources using VS2008 extensions here [1]

602 Rating: 2.8/5 (4 votes cast)