VB.NET – Masque de saisie de date dans un datagridview en winform

Sub New()

‘ Cet appel est requis par le concepteur.
InitializeComponent()

Dim dt As New DataTable
dt.Columns.Add(“a”)
dt.Columns.Add(“Date”)

Dim dr1 As DataRow = dt.NewRow
dr1.Item(“Date”) = “10/03/2013”
Dim dr2 As DataRow = dt.NewRow
dr2.Item(“Date”) = “10/03/2013”

dt.Rows.Add(dr1)
dt.Rows.Add(dr2)

MDataGridView1.DataSource = dt
afficheDataGrid(MDataGridView10, False)

maskedTextBox2 = New MaskedTextBox
With maskedTextBox2
.Mask = “00/00/0000”
.Visible = False
End With
MDataGridView10.Controls.Add(maskedTextBox2)

End Sub

Const nomColonne As String = “Date”
Private WithEvents maskedTextBox2 As MaskedTextBox

Private Sub MyDataGridView1_CellBeginEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles MDataGridView10.CellBeginEdit
If (Me.MDataGridView10.Columns(e.ColumnIndex).Name = nomColonne) Then
Dim rect2 As Rectangle = Me.MDataGridView10.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, True)
Me.maskedTextBox2.Size = rect2.Size
Me.maskedTextBox2.Location = rect2.Location
If (Me.MDataGridView10.CurrentCell.Value IsNot Nothing) Then
Me.maskedTextBox2.Text = Me.MDataGridView10.CurrentCell.FormattedValue.ToString()
End If
Me.maskedTextBox2.Visible = True
End If
End Sub

Private Sub MyDataGridView1_CellEndEdit(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles MDataGridView10.CellEndEdit
If (Me.MDataGridView10.Columns(e.ColumnIndex).Name = nomColonne) Then
Me.MDataGridView10.CurrentCell.Value = maskedTextBox2.Text
Me.maskedTextBox2.Visible = False
End If
End Sub

Private IsHandleAdded2 As Boolean

Private Sub MyDataGridView1_EditingControlShowing(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewEditingControlShowingEventArgs) Handles MDataGridView10.EditingControlShowing
If Not IsHandleAdded2 And (Me.MDataGridView10.Columns(Me.MDataGridView10.CurrentCell.ColumnIndex).Name = nomColonne) Then
Dim tx As TextBox = CType(e.Control, TextBox)
AddHandler tx.KeyPress, AddressOf Me.tx_KeyPress
IsHandleAdded2 = True
End If
End Sub

Private Sub tx_KeyPress(ByVal sender As Object, ByVal e As KeyPressEventArgs)
If (Me.MDataGridView10.Columns(Me.MDataGridView10.CurrentCell.ColumnIndex).Name = nomColonne) Then
e.Handled = True
Me.maskedTextBox2.Focus()
If (Char.IsNumber(e.KeyChar)) Then
Me.maskedTextBox2.Text = e.KeyChar.ToString()
Else
Me.maskedTextBox2.SelectAll()
End If
End If
End Sub

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s