Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

validation on button click event wpf c#

I have a WPF application where I have to check a TextBox value and a ComboBox. if it is empty or not on to the format the button click event should fire an error and if the selected index is 0 in the ComboBox again it should fire an error.(like in error provider).

I did many research on the internet I came across with the solution with IDataErrorInfo. But the problem is how do i do this on the button click event. All of the examples are doing it on the form load.

I'm quite new for WPF. following is my code

public class ClientMap : IDataErrorInfo
{
    public string CDSNo { get; set; }

    public ClientMap(int ID)
    {
        Id = ID;
    }
    public ClientMap()
    {

    }

    public string Error
    {
        get { throw new NotImplementedException(); }
    }

    public string this[string columnName]
    {
        get
        {
            string result = null;
            if (columnName == "CDSNo")
            {
                if (string.IsNullOrEmpty(CDSNo))
                    result = "Please enter a CDS No";
                else
                {
                    string regEx = "[A-Z]{3}-\\d{9}-[A-Z]{2}-\\d{2}";
                    if (!Regex.IsMatch(CDSNo, regEx))
                    {
                        result = "Invalid CDS No";
                    }
                }
            }

            return result;
        }
    }

    public int Id { get; set; }
    public CE.Data.Customer Customer { get; set; }
    public CE.Data.Institute Institute { get; set; }
    public bool Archived { get; set; }
    public DateTime DateCreated { get; set; }

}

and XAML is

<Window.Resources>
    <validation:ClientMap x:Key="data"/>
</Window.Resources>

<control:AutoCompleteTextBox Style="{StaticResource textBoxInError}">
    <TextBox.Text>
        <Binding Path="CDSNo" Source="{StaticResource data}"
                ValidatesOnDataErrors="True"   
                UpdateSourceTrigger="Explicit">

            <Binding.ValidationRules>
                <ExceptionValidationRule/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</control:AutoCompleteTextBox>

Please help me. Thanks

like image 497
Sri Avatar asked Dec 22 '12 17:12

Sri


People also ask

How to add a button click event handler in WPF?

How to add a Button click event handler in WPF? The Click attribute of the Button element adds the click event handler. The following code adds the click event handler for a Button.

Do you have any experience with validation in WPF?

In all likelihood, if you have experience working with WPF application forms, you’ve had to deal with the implementation of validation in some capacity. In spite of the large amount of choices on hand, most of them are developed to function at a “field level.”

Should user data be verified in WPF application forms?

User data warrants verification in just about every application containing these forms. In all likelihood, if you have experience working with WPF application forms, you’ve had to deal with the implementation of validation in some capacity. In spite of the large amount of choices on hand, most of them are developed to function at a “field level.

What is the difference between causesvalidation and canceleventargs?

If the CausesValidation property is set to false, the Validating and Validated events are suppressed. If the Cancel property of the CancelEventArgs is set to true in the Validating event delegate, all events that would usually occur after the Validating event are suppressed.


1 Answers

This is modified code from this article. You will need to get the references and additional classes from the download available from that site.

Window1.xaml

<Window x:Class="SOTCBindingValidation.Window1" x:Name="This"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:SOTCBindingValidation"
    Title="SOTC Validation Test" Height="184" Width="390">
    <Window.Resources>
        <local:ErrorsToMessageConverter x:Key="eToMConverter" />
    </Window.Resources>
    <StackPanel Margin="5">
        <TextBlock Margin="2">Enter An IPv4 Address:</TextBlock>
            <TextBox x:Name="AddressBox">
                <TextBox.Text>
                    <Binding ElementName="This" Path="IPAddress" 
                             UpdateSourceTrigger="Explicit">
                        <Binding.ValidationRules>
                            <local:IPv4ValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
        <TextBlock Margin="2" Foreground="Red" FontWeight="Bold" 
            Text="{Binding ElementName=AddressBox, 
                          Path=(Validation.Errors),
                          Converter={StaticResource eToMConverter}}" />
            <Button Name="Btn1" Height ="30" Width="70" Click="Btn1_Click"></Button>
    </StackPanel>

</Window>

Window1.xaml.cs

using System.Windows;
using System.Windows.Controls;
namespace SOTCBindingValidation
{

    public partial class Window1 : Window
    {
        public static readonly DependencyProperty IPAddressProperty =
            DependencyProperty.Register("IPAddress", typeof(string),
            typeof(Window1), new UIPropertyMetadata(""));

        public string IPAddress
        {
            get { return (string)GetValue(IPAddressProperty); }
            set { SetValue(IPAddressProperty, value); }
        }

        public Window1()
        { InitializeComponent(); }

        private void Btn1_Click(object sender, RoutedEventArgs e)
        {
            ForceValidation();
            if (!Validation.GetHasError(AddressBox))
            {
                // Put the code you want to execute if the validation succeeds here
            }
        }
        private void ForceValidation()
        {
            AddressBox.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

    }
}
like image 111
Mark Hall Avatar answered Oct 09 '22 09:10

Mark Hall