here's some textbox extensions:
http://www.vbforums.com/showpost.php...0&postcount=10
Printable View
here's some textbox extensions:
http://www.vbforums.com/showpost.php...0&postcount=10
this is an extension to the Date class:
vb Code:
Imports System.Globalization Module extensions ''' <summary> ''' Date class extension ''' </summary> ''' <param name="instance"></param> ''' <returns>from "3/5/2011" (d/M/yyyy) returns 3rd May 2011</returns> ''' <remarks>updated to work with all cultures</remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function toFullDateString(ByVal instance As Date) As String Dim dateString = instance.ToLongDateString Dim parts() As String = dateString.Split(" "c) Dim dayPart As Integer = Array.FindIndex(parts, AddressOf isDayPart) parts(dayPart) = parts(dayPart).TrimStart("0"c) dateString = String.Join(" ", parts) Dim insertionPoint As Integer = dateString.IndexOf(parts(dayPart)) + parts(dayPart).TrimEnd(","c).Length Dim suffix As String = "" Select Case CInt(parts(dayPart).TrimEnd(","c)) Case 1, 21, 31 suffix = "st" Case 2, 22 suffix = "nd" Case 3, 23 suffix = "rd" Case Else suffix = "th" End Select Return dateString.Insert(insertionPoint, suffix) End Function Private Function isdaypart(ByVal part As String) As Boolean Dim value As Integer Integer.TryParse(part.TrimEnd(","c), value) Return value > 0 AndAlso value <= 31 End Function End Module
edit: updated to work with all cultures
here's an extension to the DataGridViewButtonCell:
vb Code:
Module extensions Private Const MOUSEEVENTF_LEFTDOWN As Integer = &H2 Private Const MOUSEEVENTF_LEFTUP As Integer = &H4 Private Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Integer, ByVal dx As Integer, ByVal dy As Integer, _ ByVal cButtons As Integer, ByVal dwExtraInfo As Integer) Private Declare Sub SetCursorPos Lib "User32" (ByVal X As Integer, ByVal Y As Integer) <System.Runtime.CompilerServices.Extension()> _ Public Sub performClick(ByVal instance As DataGridViewButtonCell) If Not instance.Visible Then Return Dim p As Point = instance.DataGridView.PointToScreen(instance.DataGridView.GetCellDisplayRectangle(instance.ColumnIndex, instance.RowIndex, False).Location) SetCursorPos(p.X + 10, p.Y + 10) mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0) mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0) End Sub End Module
here's an extension to the string class:
http://www.vbforums.com/showpost.php...88&postcount=2
Useful extensions, but a bit of explanation and keeping to the .NET naming conventions wouldn't hurt :)
(method names start with an uppercase letter and generally do not contain abbreviations such as 'Dup' instead of 'Duplicate')
here's 2 extensions to the listbox control (descriptions in the comments Nick):
vb Code:
Module extensions ''' <summary> ''' ListBox.itemsArray ''' </summary> ''' <param name="instance"></param> ''' <returns>returns a string array containing the listbox.items as displayed</returns> ''' <remarks>works with bound + unbound listboxes</remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function itemsArray(ByVal instance As ListBox) As String() If TypeOf instance.Items(0) Is String Then Return (From item In instance.Items.Cast(Of String)()).ToArray ElseIf TypeOf instance.Items(0) Is Integer Then Return Array.ConvertAll((From item In instance.Items.Cast(Of Integer)()).ToArray, Function(i) i.ToString) Else Return (From drv In instance.Items _ Let item = DirectCast(drv, System.Data.DataRowView).Item(instance.DisplayMember).ToString _ Select item).ToArray End If End Function ''' <summary> ''' ListBox.selectedItemsArray ''' </summary> ''' <param name="instance"></param> ''' <returns>returns a string array containing the listbox.selectedItems as displayed</returns> ''' <remarks>works with bound + unbound listboxes</remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function selectedItemsArray(ByVal instance As ListBox) As String() If TypeOf instance.Items(0) Is String Then Return (From item In instance.SelectedItems.Cast(Of String)()).ToArray ElseIf TypeOf instance.Items(0) Is Integer Then Return Array.ConvertAll((From item In instance.SelectedItems.Cast(Of Integer)()).ToArray, Function(i) i.ToString) Else Return (From drv In instance.SelectedItems _ Let item = DirectCast(drv, System.Data.DataRowView).Item(instance.DisplayMember).ToString _ Select item).ToArray End If End Function End Module
here's 2 extensions to arrays of point():
vb Code:
Module extensions ''' <summary> ''' min function enum ''' </summary> ''' <remarks></remarks> Public Enum minProperty Xmin YMin End Enum ''' <summary> ''' extension to the Point() array ''' </summary> ''' <param name="instance">Point() array</param> ''' <param name="property">x or y min</param> ''' <returns></returns> ''' <remarks>Point</remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function min(ByVal instance As Point(), ByVal [property] As minProperty) As Point Dim values() As Integer = Nothing Select Case [property] Case minProperty.Xmin values = Array.ConvertAll(instance, Function(p) p.X) Case minProperty.YMin values = Array.ConvertAll(instance, Function(p) p.Y) End Select Dim lowest As Integer = values.Min Return instance(Array.IndexOf(values, lowest)) End Function ''' <summary> ''' max function enum ''' </summary> ''' <remarks></remarks> Public Enum maxProperty Xmax YMax End Enum ''' <summary> ''' extension to the Point() array ''' </summary> ''' <param name="instance">Point() array</param> ''' <param name="property">x or y max</param> ''' <returns>Point</returns> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function max(ByVal instance As Point(), ByVal [property] As maxProperty) As Point Dim values() As Integer = Nothing Select Case [property] Case maxProperty.Xmax values = Array.ConvertAll(instance, Function(p) p.X) Case maxProperty.YMax values = Array.ConvertAll(instance, Function(p) p.Y) End Select Dim highest As Integer = values.Max Return instance(Array.IndexOf(values, highest)) End Function End Module
Having that in the summary doesn't really help, as the contents of <summary> and <param> are what you see in IntelliSense first.Code:''' <summary>
''' ListBox.itemsArray
''' </summary>
''' <param name="instance"></param>
''' <returns>returns a string array containing the listbox.items as displayed</returns>
''' <remarks>works with bound + unbound listboxes</remarks>
here's a treenodes collection sorter:
vb Code:
Module extensions Public Enum sortOrder ascending descending End Enum <System.Runtime.CompilerServices.Extension()> _ Public Sub sort(ByVal instance As TreeNodeCollection, ByVal order As sortOrder) Dim nodes() As TreeNode = instance.Cast(Of TreeNode).ToArray Array.Sort(nodes, Function(x As TreeNode, y As TreeNode) If(order = sortOrder.ascending, x.Text.CompareTo(y.Text), y.Text.CompareTo(x.Text))) instance.Clear() instance.AddRange(nodes) End Sub End Module
here's the treenode collection extension with optional childnode sorting:
vb Code:
Module extensions Public Enum sortOrder ascending descending End Enum <System.Runtime.CompilerServices.Extension()> _ Public Sub sort(ByVal instance As TreeNodeCollection, ByVal order As sortOrder, Optional ByVal sortChildNodes As Boolean = False) Dim nodes() As TreeNode = instance.Cast(Of TreeNode).ToArray Array.Sort(nodes, Function(x As TreeNode, y As TreeNode) If(order = sortOrder.ascending, x.Text.CompareTo(y.Text), y.Text.CompareTo(x.Text))) instance.Clear() instance.AddRange(nodes) If sortChildNodes Then For Each node As TreeNode In nodes node.Nodes.sort(order, True) Next End If End Sub End Module
here's an extension to the Long datatype that returns the number as words:
vb Code:
Imports System.Globalization Module extensions <System.Runtime.CompilerServices.Extension()> _ Public Function toNumberString(ByVal instance As Long) As String Dim removeAmpersand As Boolean = False Dim returnString As String = "" Dim trillions As Long = instance \ 1000000000000 If trillions > 0 Then instance -= trillions * 1000000000000 returnString &= toNumberString(trillions) & " trillion " End If Dim billions As Long = instance \ 1000000000 If billions > 0 Then instance -= billions * 1000000000 returnString &= toNumberString(billions) & " billion " End If Dim millions As Long = instance \ 1000000 If millions > 0 Then instance -= millions * 1000000 returnString &= toNumberString(millions) & " million " End If Dim thousands As Long = instance \ 1000 If thousands > 0 Then instance -= thousands * 1000 returnString &= toNumberString(thousands) & " thousand " End If Dim hundreds As Long = instance \ 100 If hundreds > 0 Then instance -= hundreds * 100 returnString &= toNumberString(hundreds) & " hundred " End If If instance >= 90 Then instance -= 90 returnString &= " & ninety " removeAmpersand = True End If If instance >= 80 Then instance -= 80 returnString &= " & eighty " removeAmpersand = True End If If instance >= 70 Then instance -= 70 returnString &= " & seventy " removeAmpersand = True End If If instance >= 60 Then instance -= 60 returnString &= " & sixty " removeAmpersand = True End If If instance >= 50 Then instance -= 50 returnString &= " & fifty " removeAmpersand = True End If If instance >= 40 Then instance -= 40 returnString &= " & forty " removeAmpersand = True End If If instance >= 30 Then instance -= 30 returnString &= " & thirty " removeAmpersand = True End If If instance >= 20 Then instance -= 20 returnString &= " & twenty " removeAmpersand = True End If If instance = 19 Then returnString &= " & nineteen" instance = 0 End If If instance = 18 Then returnString &= " & eighteen" instance = 0 End If If instance = 17 Then returnString &= " & seventeen" instance = 0 End If If instance = 16 Then returnString &= " & sixteen" instance = 0 End If If instance = 15 Then returnString &= " & fifteen" instance = 0 End If If instance = 14 Then returnString &= " & fourteen" instance = 0 End If If instance = 13 Then returnString &= " & thirteen" instance = 0 End If If instance = 12 Then returnString &= " & twelve" instance = 0 End If If instance = 11 Then returnString &= " & eleven" instance = 0 End If If instance = 10 Then returnString &= " & ten" instance = 0 End If If instance = 9 Then returnString &= If(removeAmpersand, " nine", " & nine") instance = 0 End If If instance = 8 Then returnString &= If(removeAmpersand, " eight", " & eight") instance = 0 End If If instance = 7 Then returnString &= If(removeAmpersand, " seven", " & seven") instance = 0 End If If instance = 6 Then returnString &= If(removeAmpersand, " six", " & six") instance = 0 End If If instance = 5 Then returnString &= If(removeAmpersand, " five", " & five") instance = 0 End If If instance = 4 Then returnString &= If(removeAmpersand, " four", " & four") instance = 0 End If If instance = 3 Then returnString &= If(removeAmpersand, " three", " & three") instance = 0 End If If instance = 2 Then returnString &= If(removeAmpersand, " two", " & two") instance = 0 End If If instance = 1 Then returnString &= If(removeAmpersand, " one", " & one") instance = 0 End If Return returnString.TrimStart(New Char() {" "c, "&"c}).Replace(" ", " ").Trim End Function End Module
Sure, see CodeBank thread.
i haven't tried it but i don't see how 167 lines is trimmed down compared to my 155 lines:D
Well, I added negative numbers, -illions up to sextillions, fractions, decimal points, etc.
here's some extensions for 2d integer arrays:
vb Code:
Module extensions ''' <summary> ''' 2d integer array sum function ''' </summary> ''' <param name="instance"></param> ''' <returns>sum of all elements</returns> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function sum(ByVal instance(,) As Integer) As Integer Return Enumerable.Range(0, instance.GetUpperBound(0) + 1).Select(Function(i1) Enumerable.Range(0, instance.GetUpperBound(1) + 1).Select(Function(i2) instance(i1, i2)).Sum).Sum End Function ''' <summary> ''' 2d integer array sumColumn function ''' </summary> ''' <param name="instance"></param> ''' <param name="columnIndex"></param> ''' <returns>sum of column</returns> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function sumColumn(ByVal instance(,) As Integer, ByVal columnIndex As Integer) As Integer Return Enumerable.Range(0, instance.GetUpperBound(0) + 1).Select(Function(i) instance(i, columnIndex)).Sum End Function ''' <summary> ''' 2d integer array sumRow function ''' </summary> ''' <param name="instance"></param> ''' <param name="rowIndex"></param> ''' <returns>sum of row</returns> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function sumRow(ByVal instance(,) As Integer, ByVal rowIndex As Integer) As Integer Return Enumerable.Range(0, instance.GetUpperBound(1) + 1).Select(Function(i) instance(rowIndex, i)).Sum End Function End Module
this is a vb2010 extension for reading a csv file into a 2d array:
vb Code:
Module extensions ''' <summary> ''' to2DStringArray ''' </summary> ''' <param name="instance">a 1D string array</param> ''' <returns>a 2D string array</returns> ''' <remarks></remarks> <System.Runtime.CompilerServices.Extension()> _ Public Function to2DStringArray(ByVal instance As String()) As String(,) Dim csvArray(instance.GetUpperBound(0), instance(0).Split(","c).GetUpperBound(0)) As String Array.ForEach(Enumerable.Range(0, csvArray.GetUpperBound(0) + 1).ToArray, Sub(r) Array.ForEach(Enumerable.Range(0, csvArray.GetUpperBound(1) + 1).ToArray, Sub(c) csvArray(r, c) = instance(r).Split(","c)(c))) Return csvArray End Function End Module
you use it like this:
vb Code:
Dim csv(,) As String = IO.File.ReadAllLines("csv.txt").to2DStringArray()
here's a vb2008 extension that finds all controls oftype + adds them to a list(of T):
this is how you'd use it:Code:Module extensions
<System.Runtime.CompilerServices.Extension()> _
Public Sub findNestedControls(Of T)(ByVal instance As Control, ByVal ctrls As List(Of T))
ctrls.AddRange(instance.Controls.OfType(Of T).ToArray)
For Each child As Control In instance.Controls
child.findNestedControls(Of T)(ctrls)
Next
End Sub
End Module
Code:Dim textboxes As New List(Of TextBox)
Me.findNestedControls(Of TextBox)(textboxes)
Produces incorrect results when the values are quoted, egWhy not just use the TextFieldParser?Code:",",","
Re: toFullDateString: Wouldn’t something like this work?
Code:Return Me.Day.OrdinalSuffix() & Me.ToString(" MMMM yyyy")
Extracted out the ordinal aspect out into it own function. OrdinalSuffix
Now the ToFullDateStringCode:Namespace Global.Exts.Ordinals
<HideModuleName>
Public Module Exts
<Extension> Public Function OrdinalSuffix( value As Integer) As String
If value < 0 Then Return ""
If ((value \ 10) Mod 10)=1 Then Return "th"
Select Case value
Case 1:Return "st"
Case 2:Return "nd"
Case 3:Return "rd"
End select
Return "th"
End Function
And example usageCode:<Extension> Public Function ToFullDateString(d As Date) As String
return String.Format("{0}{1} {2}",d.Day, d.Day.OrdinalSuffix ,d.ToString("MMMM yyyy"))
End Function
End Module
End Namespace
Code:Dim dd = #09/27/1979#.ToFullDateString ' That's a US date literal
What he said. Except
if that works. I don’t know.Code:Return String.Format("{0:d}{1} {0:MMMM yyyy}", d.Day.OrdinalSuffix(), d)
well yeah. whatever way you want to use it. it's open to interpretation:D
that's something Microsoft should include in the next version of VS
edit: ok I tried it. your calculations are out there. try:
unless i'm very much mistaken, the 21th September 1979 never existed in this dimension:DCode:MsgBox(#9/21/1979#.ToFullDateString)
why change working code?:
Code:Select Case value
Case 1, 21, 31: Return "st"
Case 2, 22: Return "nd"
Case 3, 23: Return "rd"
Case Else: Return "th"
End Select
I’m not spamming your thread. You can make your own OrdinalSuffix extension. I was just saying that custom date formats are built into .NET; you don’t have to format it one way, split it, shuffle it, find and parse out a likely day, calculate a suffix, and put that all together just to get a date in a particular format.
I can't remember exactly why I did it that way.
I think it was to include the day name in the output string
ok. perhaps it was due for an overhaul:D
Code:Module extensions
''' <summary>
''' Date class extension
''' </summary>
''' <param name="instance"></param>
''' <returns>from "3/5/2011" (d/M/yyyy) returns Tuesday 3rd May 2011</returns>
''' <remarks></remarks>
<System.Runtime.CompilerServices.Extension()> _
Public Function toFullDateString(ByVal instance As Date, Optional ByVal era As Boolean = False, Optional ByVal utcOffset As Boolean = False) As String
Return String.Format("{0:dddd} {0:%d}{1} {0:MMMM} {0:yyyy}" & If(era, " {0:gg}", "") & If(utcOffset, " {0:zzz}", ""), instance, OrdinalSuffix(instance.Day))
End Function
Private Function OrdinalSuffix(ByVal d As Integer) As String
Select Case d
Case 1, 21, 31 : Return "st"
Case 2, 22 : Return "nd"
Case 3, 23 : Return "rd"
Case Else : Return "th"
End Select
End Function
End Module
.paul. your Ordinal only covers values 1 to 31.
A small correction to mine and it covers any ordinal
Code:Public Module Exts
<Extension> Public Function OrdinalSuffix( value As Integer) As String
If value < 0 then Return ""
If ((value \ 10) Mod 10)=1 Then Return "th"
Select Case value Mod 10
Case 1:Return "st"
Case 2:Return "nd"
Case 3:Return "rd"
End select
Return "th"
End Function
Code:Imports System.Runtime.CompilerServices
Imports System.Text.RegularExpressions
Module extensions
''' <summary>
''' Date class extension
''' </summary>
''' <param name="instance"></param>
''' <returns>from "3/5/2011" (d/M/yyyy) returns Tuesday 3rd May 2011</returns>
''' <remarks></remarks>
<Extension()> _
Public Function toFullDateString(ByVal instance As Date, Optional ByVal era As Boolean = False, Optional ByVal utcOffset As Boolean = False) As String
Return Regex.Replace(instance.ToLongDateString, String.Format("\b0?{0}\b", instance.Day), String.Format("{0:%d}{1}", instance, OrdinalSuffix(instance.Day)))
End Function
Private Function OrdinalSuffix(ByVal d As Integer) As String
Select Case d
Case 1, 21, 31 : Return "st"
Case 2, 22 : Return "nd"
Case 3, 23 : Return "rd"
Case Else : Return "th"
End Select
End Function
End Module
here's another extension to the treeview control for expanding + collapsing by node level:
this is how to use it:Code:Imports System.Runtime.CompilerServices
Module extensions
<Extension()> _
Public Sub expand(ByVal instance As TreeView, ByVal depth As Integer)
instance.CollapseAll()
recursiveExpand(instance.Nodes, depth, 0)
End Sub
Private Sub recursiveExpand(ByVal t As TreeNodeCollection, ByVal depth As Integer, ByVal startAt As Integer)
For x As Integer = startAt To depth - 1
For Each node As TreeNode In t.Cast(Of TreeNode).Where(Function(n) n.Level = x)
node.Expand()
recursiveExpand(node.Nodes, depth, x + 1)
Next
Next
End Sub
End Module
Code:Public Class Form1
Private Sub NumericUpDown1_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDown1.ValueChanged
TreeView1.expand(CInt(NumericUpDown1.Value))
End Sub
End Class