By Buck on December 31, 2009
First Declare a form level Dataset
Public Class frmCSV
Dim ds As New DataSet
Next connect to your data source and build your dataset. In this case I am going to build one on the fly with this
Private Sub BuildDS()
Dim dt As New DataTable
Dim dr As DataRow
Dim idColumn As DataColumn = _
New DataColumn("ID", Type.GetType("System.Int32"))
Dim FNColumn As DataColumn = _
New DataColumn("FirstName", Type.GetType("System.String"))
Dim LNColumn As DataColumn = _
New DataColumn("LastName", Type.GetType("System.String"))
dt.Columns.Add(idColumn)
dt.Columns.Add(FNColumn)
dt.Columns.Add(LNColumn)
dr = dt.NewRow()
dr("ID") = 1
dr("FirstName") = "Randy"
dr("LastName") = "Flag"
dt.Rows.Add(dr)
dr = dt.NewRow()
dr("ID") = 2
dr("FirstName") = "Tom"
dr("LastName") = "Servo"
dt.Rows.Add(dr)
ds.Tables.Add(dt)
End Sub
Now the code to loop trough your dataset and write the results to a file.
Private Sub WriteDS2CSV(ByVal ds As DataSet, ByVal FilePath As String)
Dim str As New System.Text.StringBuilder
For Each dr As DataRow In ds.Tables(0).Rows
For Each field As Object In dr.ItemArray
str.Append(field.ToString & ",")
Next
str.Replace(",", vbNewLine, str.Length - 1, 1)
Next
Try
My.Computer.FileSystem.WriteAllText(FilePath, str.ToString, False)
MessageBox.Show("File Created", "Success", MessageBoxButtons.OK)
Catch ex As Exception
MessageBox.Show(ex.Message, "Write Error", MessageBoxButtons.OK)
End Try
End Sub
All that is left is to actually build the dataset and then pass it as well as the file name and path to the WriteDS2CSV sub.
Private Sub btnWriteCSV_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnWriteCSV.Click
BuildDS()
WriteDS2CSV(ds, "C:\dsExport.csv")
End Sub
Posted in VB Bits
By Buck on October 27, 2009
A handy little function to remove the name part of an email address.
Public Class Form1
Public Function getNameFromEmail(ByVal strEmail As String) As String
' This purpose of this function is to return the
' name part of an email address. For instance
' joe@somewhere.com would return just joe.
' Use the IndexOf to find out how many characters
' in the @ sign is so I can use that number later
' to determine the amount of characters to select
' in the substring.
Dim i As Integer = strEmail.IndexOf("@")
Dim newstring As String = strEmail.Substring(0, i)
Return newstring
End Function
Private Sub Button1_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
Dim emailArray() As String = { _
"me@somewhere.com", _
"you@anywhere.com", _
"them@nowhere.com"}
For Each emailName As String In emailArray
Dim strMess As String = CStr(getNameFromEmail(emailName))
MessageBox.Show(strMess, "Email Name Test", _
MessageBoxButtons.OK)
Next
End Sub
End Class
Posted in VB Bits
By Buck on September 10, 2009
Imports System.Text.RegularExpressions
Public Class Form3
Private Sub btnValidate_Click( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs)
Handles btnValidate.Click
If EmailCheck(txtEmail.Text) = True Then
MessageBox.Show("The email is valid.")
Else
MessageBox.Show("Email address is invalid")
End If
End Sub
Function EmailCheck(ByVal Email As String) As Boolean
Dim ValidEmail As String = _
"^([0-9a-zA-Z]+[-._+&])*[0-9a-zA-Z]+@" & _
"([-0-9a-zA-Z]+[.])+[a-zA-Z]{2,6}$"
' If the passed in email matched the
' RegEx pattern a true will get returned.
Return Regex.IsMatch(Email, ValidEmail)
End Function
End Class
Posted in VB Bits
By Buck on September 3, 2009
I had a need for a function that would return the next birth date of a person without showing the actual birthday of that person to the end user. In the beginning I thought this was going to be a cinch to do. It wasn’t until I sat down to write the function that I realized it was not going to be quite as easy as I thought.
The trick is that when you are trying to figure out someone’s next birthday you have to figure out weather they have already had a birthday in the current year or not. So to start off I had to take a birthday like 1969, 9, 12 and bring it to the current year making it 2007, 9, 12 so that I could do a comparison.
Private Function NextBirthDay(ByVal Bday As Date) As Date
Dim myDay As New Date(Date.Today.Year, Bday.Month, Bday.Day)
End Function
Next I had to figure out whether my new date had already passed the current date.
If myDay <= Date.Today Then
myDay = myDay.AddYears(1)
End If
If it had already passed I needed to add a year onto the new date so that it would return next years birthday date and not the current years birthday date. Obviously if it hadn’t already passed it is ok to return this years birthday date. The entire function looks like this
Private Function NextBirthDay(ByVal Bday As Date) As Date
Dim myDay As New Date(Date.Today.Year, Bday.Month, Bday.Day)
If myDay <= Date.Today Then
myDay = myDay.AddYears(1)
End If
Return myDay
End Function
And can be called using NextBirthDay(BirthDate).ToShortDateString
Posted in VB Bits
By Buck on September 2, 2009
Recently I created an Inventory Adjustment program, which loaded the entire inventory into a datagridview control from a table, allowed the user to edit the numbers and then save it back to the table. The specs required that new records not be added through this adjustment program but up until today I couldn’t find anyway to prevent what I thought was something we just had to live with when using the DGV. Not being able to prevent this "New" record was causing the application to throw an error every time someone moved beyond the last record and inserted a value into one of the fields in the New Record. So I added it to my list of things to figure out later list and moved on. Then today, coincidently, I was reading the Winforms post from Tim Mackley’s Mostly Net blog and ran across this post, which is where I learned about .DefaultView.AllowNew = False.
| So I could take this |
And make it this |
 |
 |
Code behind
da = New SqlDataAdapter("Select * From tblInventory", Con)
da.TableMappings.Add("Table", "Inventory")
ds = New DataSet
Try
da.Fill(ds)
ds.Tables("Inventory").DefaultView.AllowNew = False
dgvInventory.DataSource = ds.Tables("Inventory")
Catch ex As Exception
MessageBox.Show(ex.Message, "Data Error", MessageBoxButtons.OK)
Finally
da.Dispose()
ds.Dispose()
End Try
Posted in VB Bits
By Buck on August 26, 2009
I have been interested in a VB library for Twitter almost as long as I have know about Twitter. Today I ran across Twitter-VB. Since it is going to be a while before I can delve into it I am posting the link here so I don’t lose track of it.
Posted in Social Media, VB Bits
By Buck on August 20, 2009
A quick application to delete files older then a set number of days (or any interval).
Module Module1
Sub Main()
Fdelete()
End Sub
Private Sub Fdelete()
' Set directory to delete files
Dim myDir As String = "C:\MyFiles\"
Dim mydate As Date = Now
For Each S As String In IO.Directory.GetFiles(myDir)
If DateDiff( _
DateInterval.Day, _
IO.File.GetCreationTime(S), _
mydate) >= 7 Then
' Change the 7 to change the number of days to keep.
' Anything older then 7 days will be deleted. Also
' the date interval can be changed to whatever is
' appropriate for your needs.
Try
IO.File.Delete(S)
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
End If
Next
End Sub
End Module
Posted in VB Bits