Chỉ cho nhập số nguyên:
using System;
using System.Collectoins.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace MyProject
{
puplic partial class Form1:Form
{
public Form1()
{
InitializeComponent();
txtInteger.KeyPress += new KeyPressEventHandler(txtInteger_KeyPress);
}
void txtInteger_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handle = !char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar);
}
}
}
Hàm chỉ cho phép nhập số và cho phép hiển thị định dạng tiền tệ:
private void textBox_Change(TextBox txtTextBox)
{
if (txtTextBox.Text.Trim() != "")
{
string pattern = "^(\\d{0,9}|,\\.?\\d{0,0}$)";
Regex regex = new Regex(pattern);
string text = txtTextBox.Text.Trim().Replace(",", "");
if (text.IsMatch(text) || text == "" || text == ".")
{
txtTextBox.Text = "0";
}
}
}
Định dạng tiền tệ:
private void txtHienthiTiente(TextBox txtTextBox)
{
if (txtTextBox.Text.Trim() != "")
{
txtTextBox.Text = decimal.Parse(txtTextBox.Text.Trim().Replace(",", "")).ToString("#,##0");
}
}