cutexxxpies
cutexxxpies

Reputation: 55

Why can't validate a column in DataGridView only alphabet?

i am doing a project on window form in c# i have a DataGridView with data from the database

now i want to do editing in data GridView, and i have this column call Name, but and i want to validate so that when user edit, it will only key in alphabet, like example, in the Name column row 1 has a name call Rosy Chin, then user edit to this Rosy Ch11n ...it should prompt the user say that only alphabet, i use the code below but it don't prompt me that message...however if the user edit to this 4Rosy Chin....it will appear the prompt message...can i know where am i wrong??

private void dataGridView1_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.RowIndex >= 0 && e.ColumnIndex >= 0)
    {
        //int indicator;
        int newInteger;

        if (e.ColumnIndex == 1)
        {
            if (dataGridView1.Rows[e.RowIndex].IsNewRow) return;
            String data = e.FormattedValue.ToString();

             String validate= @"^[a-zA-Z]";
             Regex nameAlphabet = new Regex(validate);
             String nameGridView = data;                 
             if(!(nameAlphabet.IsMatch(nameGridView )))
             {
                 e.Cancel = true;
                 MessageBox.Show(@"Name must be in Alphabet!");
             }
             else
                 return;
        }
}

Upvotes: 1

Views: 2488

Answers (2)

Developer
Developer

Reputation: 8636

If not try as per below

Regex nameAlphabet = new Regex(@"^[a-zA-Z\s]+$");

You can do it pro-grammatically by checking the number of spaces in the text box if space is greater than 1 or if the text box starts with an empty space you can raise the necessary message box you required

try this in your code where you validate

  int cnt = 0;
    while (TextBox1.Text.Contains(" "))
    {
        cnt++;
        if (cnt > 1)
        {
            MessageBox.show("Only a space is allowed");
            break;
        }
    }

In similar way you can test whether the textbox starts with a space or not as follows

if(textbox.text.startswith(" "))
{
    // Your message
 }

Upvotes: 0

abatishchev
abatishchev

Reputation: 100278

Try to fix your RegEx:

 ^[a-zA-Z ]+$

Description:

^ start of line
[a-zA-Z ] any letter or space
+ one or more
$ end of line

Good RegEx sandbox.


To not allow only s space:

^[A-Za-z][a-zA-Z ]+[A-Za-z]$

Link to the sandbox.

Upvotes: 2

Related Questions