Beberapa fungsi sederhana yang sering digunakan

Posted by Kamarudin • 5 minute read • Comments

1. ConvertToUpper

Sesuai namanya fungsi ini otomatis melakukan konversi ke huruf besar, fungsinya sangat sederhana sekali

C# :

private char ConvertToUpper(System.Windows.Forms.KeyPressEventArgs e)
{
    return Convert.ToChar(e.KeyChar.ToString().ToUpper());
}

VB.NET :

Private Function ConvertToUpper(e As System.Windows.Forms.KeyPressEventArgs) As Char
    Return Convert.ToChar(e.KeyChar.ToString().ToUpper())
End Function

kemudian fungsi diatas kita panggil di event KeyPress

C# :

private void txtConvertToUpper_KeyPress(object sender, KeyPressEventArgs e)
{
    e.KeyChar = ConvertToUpper(e);
}

VB.NET :

Private Sub txtConvertToUppe_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtConvertToUppe.KeyPress
    e.KeyChar = ConvertToUpper(e)
End Sub

2. ConvertToLower

Fungsi berikutnya kebalikan dari fungsi ConvertToUpper yaitu mengkonversi ke huruf kecil.

C# :

private char ConvertToLower(System.Windows.Forms.KeyPressEventArgs e)
{
    return Convert.ToChar(e.KeyChar.ToString().ToLower());
}

VB.NET :

Private Function ConvertToLower(e As System.Windows.Forms.KeyPressEventArgs) As Char
    Return Convert.ToChar(e.KeyChar.ToString().ToLower())
End Function

Untuk pemanggilannya juga masih sama di event KeyPress

C# :

private void txtConvertToLower_KeyPress(object sender, KeyPressEventArgs e)
{
    e.KeyChar = ConvertToLower(e);
}

VB.NET :

Private Sub txtConvertToLower_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtConvertToLower.KeyPress
    e.KeyChar = ConvertToLower(e)
End Sub

3. NumericOnly

Fungsi ini hanya mengizinkan input dalam bentuk angka plus titik (.) untuk desimalnya

C# :

private bool NumericOnly(System.Windows.Forms.KeyPressEventArgs e)
{
    string strValid = "0123456789.";

    if (strValid.IndexOf(e.KeyChar) < 0 && !(e.KeyChar == Convert.ToChar(Keys.Back)))
    {
        return true; // not valid
    }
    else
    {
        return false; // valid
    }
}

VB.NET :

Private Function NumericOnly(e As System.Windows.Forms.KeyPressEventArgs) As Boolean
    Dim strValid As String = "0123456789."

    If strValid.IndexOf(e.KeyChar) < 0 AndAlso Not (e.KeyChar = Convert.ToChar(Keys.Back)) Then
        ' not valid
        Return True
    Else
        ' valid
        Return False
    End If
End Function

Untuk pemanggilannya juga masih sama di event KeyPress

C# :

private void txtNumericOnly_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = NumericOnly(e);
}

VB.NET

Private Sub txtNumericOnly_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtNumericOnly.KeyPress
    e.Handled = NumericOnly(e)
End Function

Fungsi NumericOnly diatas udah oke banget, tapi sayangnya kita masih bisa menginputkan nilai seperti 25.33.1 atau 25..3.

Intinya untuk tanda titik (.) masih bisa diinputnya lebih dari satu dan ini tidak benar jadi harus kita tambahkan validasi sedikit lagi.

Pertama kita deklarsikan dulu sebuah variabel untuk menyimpan status tanda titik (.).

C# :

private bool isDecimal = false;

VB.NET :

Private isDecimal As Boolean = False

Kemudian kita tambahkan validasi di event TextChanged untuk mengetahui apakah sudah ada tanda titik yang diinputkan.

C# :

private void txtNumericOnly_TextChanged(object sender, EventArgs e)
{
    isDecimal = false;

    int index = ((TextBox)sender).Text.IndexOf(".");
    isDecimal = !(index < 0);
}

VB.NET :

Private Sub txtNumericOnly_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtNumericOnly.TextChanged
    isDecimal = False

    Dim index As Integer = DirectCast(sender, TextBox).Text.IndexOf(".")
    isDecimal = Not (index < 0)
End Sub

Terakhir kita revisi event KeyPressnya

C# :

private void txtNumericOnly_KeyPress(object sender, KeyPressEventArgs e)
{
    // tambah validasi pengecekan desimal disini
    if (isDecimal && (e.KeyChar == Convert.ToChar(".")))
    {
        e.Handled = true;
    }
    else
    {
        e.Handled = NumericOnly(e);
    }
}

VB.NET :

Private Sub txtNumericOnly_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtNumericOnly.KeyPress
    ' tambah validasi pengecekan desimal disini
    If isDecimal AndAlso (e.KeyChar = Convert.ToChar(".")) Then
        e.Handled = True
    Else
        e.Handled = NumericOnly(e)
    End If
End Sub

Yuph sampe disini fungsinya udah tambah oke :)

4. LetterOnly

Fungsi yang hanya mengizinkan input berupa huruf besar/kecil plus titik dan spasi, fungsinya mirip sekali dengan fungis NumericOnly hanya karakter yang didaftarkan saja yang berbeda.

C# :

private bool LetterOnly(System.Windows.Forms.KeyPressEventArgs e)
{
    string strValid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. ";

    if (strValid.IndexOf(e.KeyChar) < 0 && !(e.KeyChar == Convert.ToChar(Keys.Back)))
    {
        return true; // not valid
    }
    else
    {
        return false; // valid
    }

}

VB.NET :

Private Function LetterOnly(e As System.Windows.Forms.KeyPressEventArgs) As Boolean
    Dim strValid As String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ. "

    If strValid.IndexOf(e.KeyChar) < 0 AndAlso Not (e.KeyChar = Convert.ToChar(Keys.Back)) Then
        ' not valid
        Return True
    Else
        ' valid
        Return False
    End If
End Function

Cara penggunaanya juga otomatis masih sama

C# :

private void txtLetterOnly_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = LetterOnly(e);
}

VB.NET :

Private Sub txtLetterOnly_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtLetterOnly.KeyPress
    e.Handled = LetterOnly(e)
End Sub

** 5. ThousandSeparator**

Fungsi ini otomatis akan menambahkan pemisah ribuan pada inputan berupa angka.

C# :

private void SetThousandSeparator(TextBox txt)
{
    if (txt.Text.Length > 0)
    {
        try
        {
            string s = txt.Text.Replace(",", "");

            int i = int.Parse(s);
            txt.Text = string.Format("{0:###,###,###}", i);

            txt.SelectionStart = txt.Text.Length;
        }
        catch
        {
        }
    }
}

VB.NET :

Private Sub SetThousandSeparator(txt As TextBox)
    If txt.Text.Length > 0 Then
        Try
            Dim s As String = txt.Text.Replace(",", "")

            Dim i As Integer = Integer.Parse(s)
            txt.Text = String.Format("{0:###,###,###}", i)

            txt.SelectionStart = txt.Text.Length
        Catch
        End Try
    End If
End Sub

Untuk pemanggilannya di event TextChanged

C# :

private void txtThousandSeparator_TextChanged(object sender, EventArgs e)
{
    SetThousandSeparator((TextBox)sender);
}

VB.NET :

Private Sub txtThousandSeparator_TextChanged(sender As System.Object, e As System.EventArgs) Handles txtThousandSeparator.TextChanged
    SetThousandSeparator (DirectCast(sender, TextBox))
End Function

Agar fungsi SetThousandSeparator bisa bekerja dengan baik tambahkan juga validasi angkanya

C# :

private void txtThousandSeparator_KeyPress(object sender, KeyPressEventArgs e)
{
    e.Handled = NumericOnly(e);
}

VB.NET :

Private Sub txtThousandSeparator_KeyPress(sender As System.Object, e As System.Windows.Forms.KeyPressEventArgs) Handles txtThousandSeparator.KeyPress
    e.Handled = NumericOnly(e)
End Function

Kemudian set property TextAlign = Right

FUNGSI PENTING LAINNYA

6. IsEnter

Untuk mendeteksi penekan tombol Enter, sehingga bisa kita manfaatkan untuk perpindahan fokus cursor pada saat input data.

C# :

private bool IsEnter(System.Windows.Forms.KeyPressEventArgs e)
{
    return (e.KeyChar == (char)Keys.Return);
}

VB.NET :

Private Function IsEnter(e As System.Windows.Forms.KeyPressEventArgs) As Boolean
    Return (e.KeyChar = ChrW(Keys.Return))
End Function

Penggunaanya masih di event KeyPress

C# :

private void txtConvertToUpper_KeyPress(object sender, KeyPressEventArgs e)
{
    if (IsEnter(e)) SendKeys.Send("{Tab}");
}

VB.NET :

Private Sub txtConvertToUpper_KeyPress(sender As Object, e As KeyPressEventArgs)
    If IsEnter(e) Then
        SendKeys.Send ("{Tab}")
    End If
End Sub

7. IsEsc

Untuk mendeteksi penekanan tombol Esc, salah satu implementasinya adalah menutup form aktif dengan menekan tombol Esc.

C# :

private bool IsEsc(System.Windows.Forms.KeyPressEventArgs e)
{
    return (e.KeyChar == (char)Keys.Escape);
}

VB.NET :

Private Function IsEsc(e As System.Windows.Forms.KeyPressEventArgs) As Boolean
    Return (e.KeyChar = ChrW(Keys.Escape))
End Function

Nah jika pada fungsi-fungsi sebelumnya semua fungsinya kita panggil di event TextBox, untuk fungsi IsEsc akan kita panggil di event KeyPress milik objek form.

C# :

private void Form1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (IsEsc(e)) this.Close();
}

VB.NET :

Private Sub Form1_KeyPress(sender As Object, e As KeyPressEventArgs)
    If IsEsc(e) Then
        Me.Close()
    End If
End Sub

Dan jangan lupa set property KeyPreview = True

Beberapa fungsi diatas sudah saya bundle menjadi satu komponen yang bisa didownload disini.

Selamat mencoba :blush:

Comments