none
Agenda of Contacts RRS feed

  • Question

  • Hello,

    I have to make an agenda of contacts. First I put my data(name,surname,mobile,..) in textboxes and after I save them in a datagridview. I have to save some checks (for example mobile must have only 10 digits and only digits) and if all of my checks are correct then to save them in the datagridview. Here is my code which send them independently the checks. What else I need in order to send them correctly in the datagridview.

    I have a button with name button 1 which send the data in datagridview:

             

     private void button1_Click(object sender, EventArgs e)
            {

                CheckPhoneNumber();
                checkEmail();



               try
                {

                    contacts c = new contacts(textBox1.Text, textBox2.Text, long.Parse(textBox3.Text), textBox4.Text, dateTimePicker1.Text);
                    list.Add(c);
                    updateViews();
                    button8_Click(sender, e);

                }
                catch
                {

                }




            }

    And here are my checks:

     private void CheckPhoneNumber()
            {
                phonevalue = textBox3.Text;


                if (phonevalue.All(Char.IsDigit))  //
                {
                    if (phonevalue.Length < 10)  //If digits are less than 10             {
                        MessageBox.Show("Must contain 10 digits");
                    }
                    
                }
                else //If input is characters
                {
                    if (phonevalue.Length < 10)
                    {
                        MessageBox.Show("Put 10 digits");
                    }
                    else
                    {
                        MessageBox.Show("It must contain only numbers");
                    }

                }
            }

            private void checkEmail()
            {

                string email = textBox4.Text;

                Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");

                Match match = regex.Match(email);

                if (match.Success)
                {
                    label6.Visible = true;
                    label6.Text = "Email is valid";
                    
                }
                else
                {
                    label6.Visible = true;
                    label6.Text = "Email is invalid";
                }

            }

     Thank you in advance.

    • Moved by CoolDadTx Friday, June 14, 2019 5:48 PM Winforms related
    Friday, June 14, 2019 3:32 PM

All replies

  • Hello,

    I would suggest looking at using DataAnnotations for validation. This allows you to set rules on properties of a class e.g.

    namespace Sample1
    {
        public class Contact
        {
            /// <summary>
            /// Email address
            /// </summary>
            [Required(ErrorMessage = "{0} is required")]
            [DataType(DataType.EmailAddress)]
            [EmailAddress]
            public string Email { get; set; }
    
            /// <summary>
            /// Phone number
            /// </summary>
            [Required(ErrorMessage = "Mobile no. is required")]
            [CheckPhoneValidation(ErrorMessage = "{0} must be no longer than 10 using only numbers")]
            public string Phone { get; set; }
        }
    }

    To use it, in this case we are focused on validating two properties, email and phone.

    using System.Windows.Forms;
    using DataValidatorLibrary.Helpers;
    using DataValidatorLibrary.LanguageExtensions;
    
    namespace Sample1
    {
        public partial class Form1 : Form
        {
            private readonly BindingSource _bsContacts = new BindingSource();
            public Form1()
            {
                InitializeComponent();
            }
            private void ValidateSingleContactButton_Click(object sender, EventArgs e)
            {
                var contact = new Contact()
                {
                    Email = EmailTextBox.Text,
                    Phone = PhoneTextBox.Text
                };
    
                var validationResult = ValidationHelper.ValidateEntity(contact);
    
                if (!validationResult.HasError)
                {
                    _bsContacts.Add(contact);
                }
                else
                {
                    MessageBox.Show(validationResult.ErrorMessageList());
                }
    
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                dataGridView1.DataSource = _bsContacts;
            }
        }
    }
    

    There are standard validation rules or you can create your own e.g. for phone number there is a standard one but below I wrote up one that may better suit your needs.

    using System.ComponentModel.DataAnnotations;
    
    namespace DataValidatorLibrary.CommonRules
    {
        public class CheckPhoneValidationAttribute : ValidationAttribute 
        {
            public override bool IsValid(object value)
            {
                bool IsDigitsOnly(string str)
                {
                    foreach (var c in str)
                    {
                        if (c < '0' || c > '9')
                            return false;
                    }
    
                    return true;
                }
    
                if (value == null)
                {
                    return false;
                }
    
                string convertedValue = value.ToString();
    
                return !string.IsNullOrWhiteSpace(convertedValue) && 
                       IsDigitsOnly(convertedValue) && 
                       convertedValue.Length <= 10;
            }
        }
    }
    The starter library is here and the sample project here.


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Saturday, June 15, 2019 10:57 AM
    Moderator
  • Hi AndriannaTs,

    Here is a example of regular expression you can refer to.

        private void btCheck_Click(object sender, EventArgs e)
        {
            if (!IsMobile(tbPhone.Text))
                MessageBox.Show("Wrong Phone Format");
    
            if (!IsEmail(tbEmail.Text))
                MessageBox.Show("Wrong E-mail Format");
        }
    
        public bool IsMobile(string str_handset)
        {
            return Regex.IsMatch(str_handset, @"^[1]+\d{9}");
        }
    
        public bool IsEmail(string str_Email)
        {
            return Regex.IsMatch(str_Email, @"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)@([A-Za-z0-9]+)(([\.\-]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", RegexOptions.IgnoreCase);
        }

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, June 17, 2019 3:14 AM
    Moderator
  • Hi AndriannaTs,

    Is your problem solved? If so, please post "Mark as answer" to the appropriate answer. So that it will help other members to find the solution quickly if they face the similar issue.

    Regards,

    Kyle


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Thursday, June 20, 2019 8:20 AM
    Moderator