Visual Basic.Net

DateTime.ToString() Patterns

0

All the patterns:

0 MM/dd/yyyy 08/22/2006
1 dddd, dd MMMM yyyy Tuesday, 22 August 2006
2 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
3 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
4 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
5 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
6 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
7 MM/dd/yyyy HH:mm 08/22/2006 06:30
8 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
9 MM/dd/yyyy H:mm 08/22/2006 6:30
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
10 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
11 MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
12 MMMM dd August 22
13 MMMM dd August 22
14 yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
15 yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss.fffffffK 2006-08-22T06:30:07.7199222-04:00
16 ddd, dd MMM yyyy HH’:’mm’:’ss ‘GMT’ Tue, 22 Aug 2006 06:30:07 GMT
17 ddd, dd MMM yyyy HH’:’mm’:’ss ‘GMT’ Tue, 22 Aug 2006 06:30:07 GMT
18 yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss 2006-08-22T06:30:07
19 HH:mm 06:30
20 hh:mm tt 06:30 AM
21 H:mm 6:30
22 h:mm tt 6:30 AM
23 HH:mm:ss 06:30:07
24 yyyy’-‘MM’-‘dd HH’:’mm’:’ss’Z’ 2006-08-22 06:30:07Z
25 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
26 yyyy MMMM 2006 August
27 yyyy MMMM 2006 August

The patterns for DateTime.ToString ( ‘d’ ) :

0 MM/dd/yyyy 08/22/2006
The patterns for DateTime.ToString ( ‘D’ ) :
0 dddd, dd MMMM yyyy Tuesday, 22 August 2006

The patterns for DateTime.ToString ( ‘f’ ) :

0 dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
1 dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
2 dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
3 dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
The patterns for DateTime.ToString ( ‘F’ ) :
0 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
The patterns for DateTime.ToString ( ‘g’ ) :
0 MM/dd/yyyy HH:mm 08/22/2006 06:30
1 MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
2 MM/dd/yyyy H:mm 08/22/2006 6:30
3 MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
The patterns for DateTime.ToString ( ‘G’ ) :
0 MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07
The patterns for DateTime.ToString ( ‘m’ ) :
0 MMMM dd August 22
The patterns for DateTime.ToString ( ‘r’ ) :
0 ddd, dd MMM yyyy HH’:’mm’:’ss ‘GMT’ Tue, 22 Aug 2006 06:30:07 GMT
The patterns for DateTime.ToString ( ‘s’ ) :
0 yyyy’-‘MM’-‘dd’T’HH’:’mm’:’ss 2006-08-22T06:30:07


The patterns for DateTime.ToString ( ‘u’ ) :

0 yyyy’-‘MM’-‘dd HH’:’mm’:’ss’Z’ 2006-08-22 06:30:07Z
The patterns for DateTime.ToString ( ‘U’ ) :
0 dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
The patterns for DateTime.ToString ( ‘y’ ) :
0 yyyy MMMM 2006 August
/ Represents the date separator defined in the current DateTimeFormatInfo..::.DateSeparator property. This separator is used to differentiate years, months, and days.
” Represents a quoted string (quotation mark). Displays the literal value of any string between two quotation marks (“). Your application should precede each quotation mark with an escape character (\).
‘ Represents a quoted string (apostrophe). Displays the literal value of any string between two apostrophe (‘) characters.
%c Represents the result associated with a c custom format specifier, when the custom date and time format string consists solely of that custom format specifier. That is, to use the d, f, F, h, m, s, t, y, z, H, or M custom format specifier by itself, the application should specify %d, %f, %F, %h, %m, %s, %t, %y, %z, %H, or %M. For more information about using a single format specifier, see Using Single Custom Format Specifiers.

Building a custom DateTime.ToString Patterns

The following details the meaning of each pattern character. Not the K and z character.
d Represents the day of the month as a number from 1 through 31. A single-digit day is formatted without a leading zero
dd Represents the day of the month as a number from 01 through 31. A single-digit day is formatted with a leading zero

ddd Represents the abbreviated name of the day of the week (Mon, Tues, Wed etc)
dddd Represents the full name of the day of the week (Monday, Tuesday etc)
h 12-hour clock hour (e.g. 7)
hh 12-hour clock, with a leading 0 (e.g. 07)
H 24-hour clock hour (e.g. 19)
HH 24-hour clock hour, with a leading 0 (e.g. 19)
m Minutes
mm Minutes with a leading zero
M Month number
MM Month number with leading zero
MMM Abbreviated Month Name (e.g. Dec)
MMMM Full month name (e.g. December)
s Seconds
ss Seconds with leading zero
t Abbreviated AM / PM (e.g. A or P)
tt AM / PM (e.g. AM or PM
y Year, no leading zero (e.g. 2001 would be 1)
yy Year, leadin zero (e.g. 2001 would be 01)
yyy Year, (e.g. 2001 would be 2001)
yyyy Year, (e.g. 2001 would be 2001)
K Represents the time zone information of a date and time value (e.g. +05:00)
z With DateTime values, represents the signed offset of the local operating system’s time zone from Coordinated Universal Time (UTC), measured in hours. (e.g. +6)
zz As z but with leadin zero (e.g. +06)
zzz With DateTime values, represents the signed offset of the local operating system’s time zone from UTC, measured in hours and minutes. (e.g. +06:00)
f Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value.
ff Represents the two most significant digits of the seconds fraction; that is, it represents the hundredths of a second in a date and time value.
fff Represents the three most significant digits of the seconds fraction; that is, it represents the milliseconds in a date and time value.
ffff Represents the four most significant digits of the seconds fraction; that is, it represents the ten thousandths of a second in a date and time value. While it is possible to display the ten thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock’s resolution is approximately 10-15 milliseconds.
fffff Represents the five most significant digits of the seconds fraction; that is, it represents the hundred thousandths of a second in a date and time value. While it is possible to display the hundred thousandths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock’s resolution is approximately 10-15 milliseconds.
ffffff Represents the six most significant digits of the seconds fraction; that is, it represents the millionths of a second in a date and time value. While it is possible to display the millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock’s resolution is approximately 10-15 milliseconds.
fffffff Represents the seven most significant digits of the seconds fraction; that is, it represents the ten millionths of a second in a date and time value. While it is possible to display the ten millionths of a second component of a time value, that value may not be meaningful. The precision of date and time values depends on the resolution of the system clock. On Windows NT 3.5 and later, and Windows Vista operating systems, the clock’s resolution is approximately 10-15 milliseconds.
F Represents the most significant digit of the seconds fraction; that is, it represents the tenths of a second in a date and time value. Nothing is displayed if the digit is zero.
: Represents the time separator defined in the current DateTimeFormatInfo..::.TimeSeparator property. This separator is used to differentiate hours, minutes, and seconds.

Make a Textbox that accepts only numbers

3
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
Const pstr As String = "0123456789"
If pstr.IndexOf(e.KeyChar) = -1 Then
e.Handled = True
End If
End Sub

If you want to add “.” for exmaple to the combination you can change first line to

Const pstr As String = "0123456789"

Prevent Adding Items to combobox

0
Private Sub ComboBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
 e.KeyChar = ChrW(0)
End Sub

Clearing all textboxes on a Form

0

Do you have a form that has a lot of textboxes?

do you want to clear all those textboxes for example when there is a new?

this is the old scenario:

TextBox1.Text = ""
TextBox2.Text = ""
TextBox3.Text = ""
TextBox4.Text = ""
TextBox5.Text = ""

etc…………
this is my idea:

Sub ClearForm(ByVal frm_name As Form)
Dim Contrl As Control
For Each Contrl In frm_name.Controls
If (TypeOf Contrl Is TextBox) Then Contrl.Text = ""
Next Contrl
End Sub

this is my friend samir ibrahim‘s idea, compatible with “.net framework 3.5 +”

For Each _Ctrl As Control In Me.Controls.OfType(Of TextBox)()
_Ctrl.Text = ""
Next

The second idea is more optimized with same result.

Of course my idea is cooler because i made it :mrgreen:

you just need to pass the form name to the function & it will clear the form for you, this will save your fingers extensive redundant typing :mrgreen::mrgreen::mrgreen::mrgreen::mrgreen:

Single Field to Multiple Rows

1

You want your field from all in one field

(No column name)
———————–
Mike,Joe,Jerry,Ben

to become separate rows like below?

NAME
——–
Mike
Joe
Jerry
Ben

then use script below..

declare @toRowXML xml
SET @toRowXML = '<b><x>'+replace('Mike,Joe,Jerry,Ben',',','</x><x>')+'</x></b>'
SELECT @toRowXML
SELECT rtrim(ltrim(toRow.value('.','nvarchar(100)'))) as NAME
 from @toRowXML.nodes('/b/x') as t(toRow)

Coalesce another IsNull method

0
COALESCE ( expression [ ,...n ] )

Coalesce is Equivalent with

CASE WHEN (expression1 IS NOT NULL) THEN expression1 WHEN (expression2 IS NOT NULL) THEN expression2 … ELSE expressionN END
END

My little experiment with coalesce

DECLARE @i VARCHAR(20)
DECLARE @exp2
SET @exp2 = NULL

SET @i = null
SELECT COALESCE (@i + ‘ more;’, ‘It”s Null’) –result [It’s Null]
SELECT COALESCE (@i , ‘ more;’, ‘Stranger’) –result [ more;]
SELECT COALESCE (@i , @exp2, ‘Stranger’) –result [Stranger]

SET @i = ‘Something’
SELECT COALESCE (@i + ‘ more;’, ‘It”s Null’) –result [Something more;]
SELECT COALESCE (@i , ‘ more;’, ‘Stranger’) –result [Something]
SELECT COALESCE (@i , @exp2 , ‘Stranger’) –result [Something]

As you see if I use case and combine it with null function it’ll need more than one line. Coalesce is very useful and helpful in above case.

Validate data entered into textboxcolumn

0

To validate the text entered into a datagrid add a handler to the DatagridTextboxColumn’s validating event. Here is some sample code.

Dim ds As New DataSet

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim conn As SqlConnection
Dim strConn As String
Dim strSQL As String
Dim da As SqlDataAdapter

strConn = “Server = (local);”
strConn &= “Database = NorthWind;”
strConn &= “Integrated Security = SSPI;”

conn = New SqlConnection(strConn)
da = New SqlDataAdapter(“Select * From Products”, conn)
da.Fill(ds, “Products”)

Dim ts As New DataGridTableStyle
ts.MappingName = ds.Tables(“Products”).TableName

Dim colDiscontinued As New DataGridBoolColumn
With colDiscontinued
.MappingName = “Discontinued”
.HeaderText = “Discontinued”
.Width = 80
End With

Dim colName As New DataGridTextBoxColumn
With colName
.MappingName = “ProductName”
.HeaderText = “Product Name”
.Width = 180
End With
AddHandler colName.TextBox.Validating, AddressOf CellValidating

ts.GridColumnStyles.Add(colName)
ts.GridColumnStyles.Add(colDiscontinued)

DataGrid1.TableStyles.Add(ts)

ts = Nothing
colDiscontinued = Nothing
colName = Nothing

DataGrid1.DataSource = ds.Tables(“Products”)
End Sub

Private Sub CellValidating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs)
Debug.WriteLine(DirectCast(sender, DataGridTextBox).Text)
End Sub

Format input date in datagridview

0

A common problem faced in datagridview is how to format the date in the grid, here is a small way to do it:

Private Sub dataGridView1_CellParsing(ByVal sender As Object, ByVal e As DataGridViewCellParsingEventArgs)

If e.ColumnIndex = 0 Then

Dim [date] As String = DirectCast(e.Value, String)

Try

Dim month As String = [date].Substring(0, 2)

Dim day As String = [date].Substring(2, 2)

Dim year As String = [date].Substring(4, 4)

e.Value = New DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day))

e.ParsingApplied = True
Catch ex As Exception

MessageBox.Show(“parsing error!”)

End Try

End If
End Sub

Hacking the Report Viewer Redistributable

0

We always face a problem when we want to publish an application, we want to make sure not to make the customer go through Library installation & dll’s & ocx’s registration, the ideal scenario is to give the customer a portable application that does not need any configuration of course that is hard to achieve especially when you have databases that need servers but you can do that with small to medium sized applications.

error

error

Today i’m going to address a different problem i faced on one of the projects i’m working on currently. I thought of using report viewer included in visual studio 2008 & 2005 keeping away from crystal reports, thinking that microsoft report viewer is included in the .net framework which turned out to be wrong.

Microsoft includes the pack for this as a standalone installation found here:

Microsoft Report Viewer Redistributable 2005 Service Pack 1:

http://www.microsoft.com/downloads/details.aspx?FamilyID=82833F27-081D-4B72-83EF-2836360A904D&displaylang=en

Microsoft Report Viewer Redistributable 2008 Service Pack 1:

http://www.microsoft.com/downloadS/details.aspx?familyid=BB196D5D-76C2-4A0E-9458-267D22B6AAC6&displaylang=en

Next use any of your zip extraction program to extract the ReportViewer.exe

You will see a CAB file named vb_ros.cab also extract it.

————————————————————————————————————————————–

Then do as following:

  1. Rename: FL_Microsoft_ReportViewer_Common_dll_117718_____X86.3643236F_FC70_11D3_A536_0090278A1BB8 To Microsoft.ReportViewer.Common.dll
  2. Rename: FL_Microsoft_ReportViewer_ProcessingObject_125592_____X86.3643236F_FC70_11D3_A536_0090278A1BB8 To Microsoft.ReportViewer.ProcessingObjectModel.dll
  3. Rename: FL_Microsoft_ReportViewer_WebForms_dll_117720_____X86.3643236F_FC70_11D3_A536_0090278A1BB8 To Microsoft.ReportViewer.WebForms.dll
  4. Rename: FL_Microsoft_ReportViewer_WinForms_dll_117722_____X86.3643236F_FC70_11D3_A536_0090278A1BB8 To Microsoft.ReportViewer.WinForms.dll

Now go to your project.

copy paste the renamed dlls, next to your exe file for exapmple “Myproject\bin\..”

now right click on your project, press properties.

go to references tab

press add -> reference -> browse -> choose the 4 dll’s

That’s it, now your project can work as a portable standalone project with report viewer support.

Thank you for reading.

Please check the youtube video if you like a more step by step tutorial

Managing BindingSource Position in Data Driven WinForms

0

If you are working with a Windows Form where a user can create and edit data in the same form you may run into the problem of trying to set the BindingSource to a given record in a DataSet you want to work with.

For example let’s say you have a DataGridView in a Smart Client.  When the user double clicks a given row in the DataGridView a form opens so they can edit the data.  More times than not (no matter how many demos you watch) user’s do not edit data values in DataGridViews.  Although this is a supported feature, business objects are too complex.  Imagine having to edit a contact in a single row in Outlook for example, not fun and not very user friendly.  Why every Microsoft demo I watch shows editing in DataGridViews is beyond me.  I digress though.

When the new form is instantiated we need to pass two things:  the dataset we are working with, and the IDof the item we want to edit.  We can pass this information into the constructor of the form without any trouble as seen below. By passing in the DataSet we can add new records, delete records or whatever we need to do.  The other benefit is since the dataset is passed by reference, any changes to it will automatically appear in the row the user just double clicked on.  In order for the form fields to be auto bound to the record the user clicked on we need to set the DataBinding of the controls in the form to a BindingSource.  The BindingSource serves as the go between between the UI and data store.    Here’s a sample “CellDoubleClick” event that would happen in the DataGridView:

1 int id = Convert.ToInt32(DataGridView.Rows[e.RowIndex].Cells[0].Value);

2 MyForm myForm = new MyForm(dataSet, id);

3 myForm.Show();

As the form loads the problem we face is having to tell the BindingSource in the form which record we want to set as the BindingSource.Current item.  At first glance it looks like we would just get the DataRow and then set it as the Current property.  Wrong.  The BindingSource.Current property has only a get accessor.  Instead we need to use the BindingSource.Position property.  Note:  Any change to the position property updates the current property used by the bindingsource.  The problem we face now is the BindingSource.Position property wants to know the index of the item in the underlying DataSource.

We don’t know the index value used by the BindingSource but we do know the ID we want to use.  This is where the BindingSource.Find() method comes in.  Using the find method we can basically search the underlying datasource and retrieve the index of a given item.  Here’s an example:

contactBindingSource.Position = contactBindingSource.Find(“Id”, 2);

Once the line above runs, it is going to search the column “Id” in the DataSource associated with the BindingSource and return the index of that item.

What if you use the same form to create a new item?  Simple, call the BindingSource.AddNew() method which will add a new item to the underlying DataSource.  Then move the index to the last item.  Here’s a sample:

bindingSource.AddNew();
bindingSource.MoveLast();

Since items are always added at the end of the associated data source the MoveLast() method will set the index to the last item in the underlying datasource.

I hope this makes sense because it is an easy way to have a form bound to a DataSet and use the same form to perform “CRUD” operations with.

Go to Top