I am trying to force a certain format into a textbox with the keypress method
private void textbox_KeyPress(object sender, KeyPressEventArgs e){
switch (((TextBox)sender).Name){
case "txtTitle":
//code
break;
case "txtDate":
if(txtDate.Text.Count() > 9) e.Handled = true;
else{
switch (txtDate.Text.Count()){
case 0: //0,1,2,3 (day)
e.Handled = (e.KeyChar > 47 && e.KeyChar < 52)?false:true;
break;
case 1: //if last was 0,1,2 accept 0-9 (day)
if (txtDate.Text.Last() > 47 && txtDate.Text.Last() < 51) e.Handled = (e.KeyChar > 47 && e.KeyChar < 58)?false:true;
//if last was 3 accept 0,1
else if (txtDate.Text.Last() == 51) e.Handled = (e.KeyChar == 48 || e.KeyChar == 49)?false:true;
break;
case 2: case 5: // '/'
if (e.KeyChar != 47) e.Handled = true;
break;
case 3: //0,1 (month)
e.Handled = (e.KeyChar == 48 || e.KeyChar == 49)?false:true;
break;
case 4: //if last was 0 accept 0-9 (month)
if(txtDate.Text.Last() == 48) e.Handled = (e.KeyChar > 47 && e.KeyChar < 58)?false:true;
//if last was 0 accept 0-9
else e.Handled = (e.KeyChar > 47 && e.KeyChar < 51)?false:true;
break;
case 6: case 7: case 8: case 9: //0-9 (year)
e.Handled = (e.KeyChar > 47 && e.KeyChar < 58)?false:true;
break;
}
}
break;
case "txtBegin": case "txtEnd":
//code
break;
}
if (e.KeyChar == 8) e.Handled = false; //backspace
}
but when I have a complete date and I want to change any numbers I can't inforce chars because I am using the text count so is there any way to use the textbox's cursor position instead of the text count
TextBox.SelectionStart
will give you the location of the caret.
If no text is selected in the control, this property indicates the insertion point, or caret, for new text
That said, you are aware that there is already a control for capturing dates from a user? It's called the DateTimePicker
. It has a Format
property that can be used to control how the date is displayed to the user.
If you're using WPF, a quick look at the properties on TextBox
shows that it has a TextBox.CaretIndex
to get you the location of the caret.
And the control for capturing a date from the user is DatePicker
.