Em có 1 cái datagridview, hiện danh sách danh bạ, em muốn khi giới hạn số ký tự nhập vào ở cột HoTen là 30 ký tự thôi, nếu nhập hơn thì sẽ có thông báo, em dùng RegEx để so sánh cái chuỗi nhập vào nhưng khi nhập ít hơn 30 ký tự vẫn bị nhận thông báo nhắc nhở. Đây là code của em:
[C#]
Đây là CSDL
mediafire.com/?wol418u8p8i9fro
cái RegEx của em zậy là đúng hay sai?
[C#]
Mã:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace demoRegExWithDGV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'demoRegexDataSet.DanhBa' table. You can move, or remove it, as needed.
this.danhBaTableAdapter.Fill(this.demoRegexDataSet.DanhBa);
}
private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
DataGridViewColumn currentCol = dataGridView1.Columns[e.ColumnIndex];
DataGridViewCell currentCel = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
if (currentCol.Name == "HoTen")
{
MessageBox.Show(currentCel.FormattedValue.ToString().Length.ToString());
if (KiemTraChieuDaiChuoi(currentCel.FormattedValue.ToString()) == false)
{
MessageBox.Show("Không được nhập nhiều hơn 30 ký tự");
}
}
}
private bool KiemTraChieuDaiChuoi(string p)
{
Regex ex = new Regex(@"^\w{1,30}$");
return ex.IsMatch(p);
}
}
}
Đây là CSDL
mediafire.com/?wol418u8p8i9fro
cái RegEx của em zậy là đúng hay sai?
