'Replacing a single quote with two single quotes in a two-way bound textbox
I have a WPF application that has a text box with a two-way binding. The XAML code looks like this:
<TextBox materialDesign:HintAssist.Hint="Name*" materialDesign:HintAssist.HintOpacity="10" materialDesign:HintAssist.Background="White" materialDesign:ValidationAssist.Background="White" materialDesign:HintAssist.Foreground="#FF002655" Style="{StaticResource MaterialDesignOutlinedTextFieldTextBox}" x:Name="txtboxFirstName" Width="260" TextChanged="txtboxFirstName_TextChanged">
<Binding Path="FirstName" UpdateSourceTrigger="PropertyChanged" Mode="TwoWay" Source="{StaticResource MyConfigs}">
<Binding.ValidationRules>
<local:TextBoxValidation ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox>
And the code behind looks like this:
private void txtboxFirstName_TextChanged(object sender, TextChangedEventArgs e)
{
MyConfigs.FirstName = txtboxFirstName.Text;
((MainWindow)System.Windows.Application.Current.MainWindow).ValidIntroductionConfigs();
}
I am trying to do the following here:
- If the user enters a single quote
'here, it should be replaced with''in the MyConfigs.FirstName because otherwise it causes issues in SQL queries. - When the app is loaded up it takes up the value from the
MyConfigs.FirstNameconfiguration. And if that contains'', it should display them as'.
For example: I enter O'Brian here. Now, O'Brian should be saved as O''Brian in MyConfigs.FirstName however, when I load it up, it should display O'Brian which is the real name.
When I did this, it just kept on replacing ' with '' and made it something like O''''''Brian. It kept on going so I just kept on getting more single quotes.
private void txtboxFirstName_TextChanged(object sender, TextChangedEventArgs e)
{
if (txtboxFirstName.Text.Contains("'"))
{
MyConfigs.FirstName = txtboxFirstName.Text.Replace("'", "''");
}
if (MyConfigs.FirstName.Contains("''"))
{
txtboxFirstName.Text = MyConfigs.FirstName.Replace("'", "''");
}
MyConfigs.FirstName = txtboxFirstName.Text;
((MainWindow)System.Windows.Application.Current.MainWindow).ValidIntroductionConfigs();
}
Solution 1:[1]
Seems like you did not correctly set the Replace arguments for the second replacement. You should switch it to this:
txtboxFirstName.Text = MyConfigs.FirstName.Replace("''", "'");
Otherwise every ' in MyConfigs.FirstName will be replaced by ''. That's why you get O''''Brian output.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | plori |
