Reputation:
I have a masked textbox for date:
<xctk:MaskedTextBox x:Name="txtDataNasc" Mask="##/##/####" HorizontalAlignment="Left" Height="27" TextWrapping="Wrap" VerticalAlignment="Top" Width="199" Margin="121,133,0,0" TextChanged="txtDataNasc_TextChanged"/>
And on that textbox Text_Changed
property I parse it's value to DateTime:
_student.Student_birthDate = DateTime.ParseExact(txtDataNasc.Text.ToString(), "yyyy-MM-dd h:mm tt", CultureInfo.InvariantCulture);
But it's not a valid DateTime String. I tried:
stg.Replace("/", "-").Replace("#", "");
But it's still keeping the textMask. How do I remove the mask on parse?
The all thing on TextChanged
looks like this:
string stg = txtDataNasc.Text.ToString();
stg.Replace("/", "-").Replace("#", "");
stg = stg + " 00:00:00";
_student.Student_birthDate = DateTime.ParseExact(txtDataNasc.Text.ToString(), "yyyy-MM-dd h:mm tt", CultureInfo.InvariantCulture);
Upvotes: 0
Views: 1223
Reputation: 169200
A mask is a mask and a value is a value. Two different things. Also your mask doesn't match the yyyy-MM-dd format so the DateTime.ParseExact
method will always fail. The sample code you have posted doesn't make much sense. Try this:
private void txtDataNasc_TextChanged(object sender, TextChangedEventArgs e)
{
string stg = txtDataNasc.Text;
if (!string.IsNullOrEmpty(stg))
{
stg += " 00:00:00";
DateTime date = default(DateTime);
if (DateTime.TryParseExact(stg, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
{
_student.Student_birthDate = date;
}
}
}
This will work if you put in 29-01-2017 in the TextBox. If you want to use another date format you should modify the format string that you pass to the DateTime.TryParseExact
method as well as the value of the Mask property of the MaskedTextBox
.
Also note that you won't be able to convert the string to a valid DateTime
and set the Student_birthDate property until the full date has been typed into the MaskedTextBox
.
Upvotes: 1