1.11M Members

Textbox that only allows time to enter in C#

 
0
 

i want the user should enter only time in the textbox in C#.e.g 09:00:00
how it is possible?

 
0
 

Use a DateTimePicker with the Format set to Time.

 
0
 

Give me a min. I'll help out.

 
0
 

Okay so this source has a few errors in it but it should give you a basic idea. Then you can either figure out how to use Convert.ToDateTime(bool Value); or you can use substrings to retrieve and convert the values. The snippet of substrings for this that I typed up is a little long and can be shortened greatly, so jusst go through and see if you can figure it out from there. I don't give people exact code they are looking for, but this code is close to what you want and the time isn't any more difficult than this.

private void textBox1_TextChanged(object sender, EventArgs e)
        {
            textBox1.MaxLength = 8;

            DeleteChars();

            if (textBox1.Text.Length == 2)
                textBox1.Text += ":";

            else if (textBox1.Text.Length == 5)
                textBox1.Text += ":";

            textBox1.SelectionStart = textBox1.Text.Length;
        }

        private void DeleteChars()
        {
            if (!textBox1.Text.EndsWith("0") && !textBox1.Text.EndsWith("1") && !textBox1.Text.EndsWith("2") && !textBox1.Text.EndsWith("3") && !textBox1.Text.EndsWith("4") && !textBox1.Text.EndsWith("5") && !textBox1.Text.EndsWith("6") && !textBox1.Text.EndsWith("7") && !textBox1.Text.EndsWith("8") && !textBox1.Text.EndsWith("9") && !textBox1.Text.EndsWith(":"))
                SendKeys.Send("{BACKSPACE}");
        }

Substrings:

int Month = 0;
int Day = 0;
int Year = 0;

string x = "";

x += textBox1.Text.Substring(0, 1);
x += textBox1.Text.Substring(1, 1);

Month = Convert.ToInt32(x);
x = "";

x += textBox1.Text.Substring(3, 1);
x += textBox1.Text.Substring(4, 1);

Day = Convert.ToInt32(x);
x = "";

x += textBox1.Text.Substring(6, 1);
x += textBox1.Text.Substring(7, 1);

Year = Convert.ToInt32(x);

DateTime dt = new DateTime();

dt.Month = Month;
dt.Day = Day;
dt.Year = 1900 + Year;
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
View similar articles that have also been tagged: