0

I'm new to WPF i need to get validations for my three TextBoxes.I tried but couldn't succeed please help me with the code needed.Please suggest me where should i make changes and corrections to get validation

This is my Xaml code

<Window x:Class="DataGrid_DataBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="IDDATA" Height="350" Width="525">

<Label  Content="ID :" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="26" Width="27"/>
<Label  Content="Name :" HorizontalAlignment="Left" Margin="10,60,0,0" VerticalAlignment="Top" Height="26" Width="48"/>
<Label  Content="Salary :" HorizontalAlignment="Left" Margin="10,110,0,0" VerticalAlignment="Top" Height="26" Width="47"/>

<TextBox Name="tb1" HorizontalAlignment="Left" Height="20" Margin="60,10,0,0" TextWrapping="NoWrap" Text="{Binding SelectedItem.Id, ElementName=dgsample,ValidatesOnNotifyDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="100" />

<TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="{Binding SelectedItem.Name, ElementName=dgsample,ValidatesOnNotifyDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True}" VerticalAlignment="Top" Width="100"/>
<TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="{Binding SelectedItem.Salary, ElementName=dgsample,ValidatesOnNotifyDataErrors=True,ValidatesOnExceptions=True,NotifyOnValidationError=True}" VerticalAlignment="Top" Width="100"/>

<Button Content="Get" HorizontalAlignment="Left" Margin="10,190,0,0" VerticalAlignment="Top" Width="75" Click="Get_Click" />
<Button Content="Add" HorizontalAlignment="Left" Margin="10,230,0,0" VerticalAlignment="Top" Width="75" Click="Add_Click" />
<Button Content="Delete" HorizontalAlignment="Left" Margin="10,270,0,0" VerticalAlignment="Top" Width="75" Click="Delete_Click" />

This is .cs Code

 public partial class MainWindow : Window
{

ObservableCollection<User> Users = new ObservableCollection<User>();
public MainWindow()
{
    InitializeComponent();

    Users.Add(new User() { Id = 101, Name = "allen", Salary = 10 });
    Users.Add(new User() { Id = 102, Name = "scott", Salary = 20 });
    Users.Add(new User() { Id = 103, Name = "mickey", Salary = 30 });
    Users.Add(new User() { Id = 104, Name = "micheal", Salary = 40 });
    Users.Add(new User() { Id = 105, Name = "fletch", Salary = 50 });
    Users.Add(new User() { Id = 106, Name = "etcher", Salary = 60 });

    dgsample.ItemsSource = Users;

}
private void DG1_AutoGeneratingColumn(object sender, DataGridAutoGeneratingColumnEventArgs e)
{
    switch (e.Column.Header.ToString())
    {
        case "Id":

            e.Column.Visibility = Visibility.Hidden;
            break;
        case "Name":
            e.Column.Visibility = Visibility.Hidden;
            break;
        case "Salary":
            e.Column.Visibility = Visibility.Hidden;
            break;
    }
}

private void Get_Click(object sender, RoutedEventArgs e)
{


    int index;
    if (int.TryParse(this.tb1.Text, out index))
    {
        User currentUser = Users.FirstOrDefault(Select => Select.Id == int.Parse(tb1.Text));
        if (currentUser != null)
        {
            this.tb2.Text = currentUser.Name;
            this.tb3.Text = currentUser.Salary.ToString();
        }
        else
            MessageBox.Show("User with the provided ID does not Exist", "Error");
    }
    else
        MessageBox.Show("ID entered is not valid number", "Error");





}



private void Add_Click(object sender, RoutedEventArgs e)
{


    if (!tb1.Text.Equals(""))
    {
        var adduser = Users.Where(User => User.Id == int.Parse(tb1.Text));

        if (!adduser.Any())
        {
            Users.Add(new User() { Id = int.Parse(tb1.Text), Name = tb2.Text, Salary = int.Parse(tb3.Text) });
        }

        else

            MessageBox.Show("Someone already has that ID.");

    }

}

private void Delete_Click(object sender, RoutedEventArgs e)
{
    int index;
    if (int.TryParse(this.tb1.Text, out index))
    {
        User currentUser = Users.FirstOrDefault(Select => Select.Id == int.Parse(tb1.Text));
        if (currentUser != null)
        {
            Users.Remove(currentUser);
        }
        else
            MessageBox.Show("User with the provided ID does not Exist", "Error");
    }
    else
        MessageBox.Show("ID entered is not valid number", "Error");

}
user2889489
  • 667
  • 2
  • 9
  • 11
  • i assume that your textboxes bind to a users object(SelectedItem) - if so your user object should implement INotifyDataErrorInfo – blindmeis Oct 24 '13 at 07:19

1 Answers1

0

It seems duplication of same question you posted here WPF TextBox Validation C#.

Did you try the solution which i suggested you to resolve it. That's very simple, just give a try copy and paste the whole code and run it. I have added only one text box to present the validation on user entered data. you can simulate the same logic in your application.

Community
  • 1
  • 1
saurabh.mridul
  • 177
  • 1
  • 11
  • I just re-tried to run the solution by myself and it works completely fine. could you be more elaborate to tell what's not working ? Are you getting any errors ( compilation/runtime) ?? – saurabh.mridul Oct 24 '13 at 07:12
  • You are seeing exceptions cos you are throwing exceptions to validate the entered data. That's not a problem when you will run the application from application assembly instead running from VS. And yes, You can see the error in UI itself by just mouse hovering on text box as it's getting displayed in tooltip. if you want to display in some other way, you can always update template style. – saurabh.mridul Oct 24 '13 at 08:23
  • Defaulty when i execute it shows 0 in the textbox how can i remove it – user2889489 Oct 24 '13 at 10:37
  • You can initialize your properties with Null or String.Empty at tge time of declaration which you are using in binding with TextBoxes. – saurabh.mridul Oct 24 '13 at 10:41
  • there is nothing to write code for that...you share your code i will check and edit the same. – saurabh.mridul Oct 24 '13 at 14:36