C# .NET - In winforms how can we validate a grid view column with phone numbers

Asked By kavitha varma on 30-Jun-12 07:46 AM
Super Man replied to kavitha varma on 30-Jun-12 01:25 PM

You can make use of cellEndEdit event of datagridview.

Just add one evnet handler:


dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);


  private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
            int row = dataGridView1.CurrentCell.RowIndex;
          int column = dataGridView1.CurrentCell.ColumnIndex;
          string item = dataGridView1[column, row].Value.ToString();
         // Here you can put extra condition to check item is valid or not.
             if (item.Length < 10)
            MessageBox.Show("The number is too short, it has to be 10 characters long.\nPlease repair the entry...", "Too short number");
            bShowing = true;



Lalit M replied to kavitha varma on 30-Jun-12 03:44 PM
You want to have a code behind function to return your formatted text. This function will allow you to have uniform formatting across all of your phone numbers. And if you ever need to change the formatting, you just need to change a single method.

public object FormatPhoneNumber(string phoneNumber)
   // return nothing if the string is null
     return "";    

   // invalid phone number submitted
   if(phoneNumber.Length != 10)
     throw new System.ArgumentException("Phone Number must contain 10 digits", "phoneNumber");

   // probably want one more check to ensure the string contains numbers and not characters, but then again, hopefully that's handled on input validation.

   // if the int is valid, return the formatted text
   return string.Format("({0}) {1}-{2}",
      phoneNumber.Substring(0, 3),
      phoneNumber.Substring(3, 3),

And you call it from your aspx page like this.

    <asp:Label ID="Label4" runat="server" Text='<%# FormatPhoneNumber(Eval("OrgContactPhone").ToString()) %>'></asp:Label>