Search code examples
c#substringis-emptymaskedtextboxisnullorempty

c# Avoid empty characters on maskedTextBox


I've read a lot about how to avoid empty maskedtextbox but none of the worked

In a click of a button I sepperate the maskedTextBox to three string , so when substring comes the application crash .

Is there anyway that I can replace the empty characters with "0" and then add them into a string , or something like that ?

CODE:

        void click(object sender, EventArgs e)
        {
            string masked = Maskedtextboxes[Convert.ToInt32(((Button)sender).Tag)].Text;

            string hh = masked.Substring(0,2), mm = masked.Substring(3,2),
            ss = masked.Substring(6,2);

            MessageBox.Show(hh+mm+ss);
        }

my maskedtextbox is masked in --/--/--


Solution

  • This should work:

      var p = masked.Split('/');
      // here you could check for p.Length == 3
      string hh = p[0].Trim().PadLeft(2, '0');
      string mm = p[1].Trim().PadLeft(2, '0');
      string ss = p[2].Trim().PadLeft(2, '0');