1

I'm just getting started with WPF and particularly Validations and DataBinding.

This is my XAML code

<Window x:Class="simpledatagrid.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">
<Grid  >
    <DataGrid SelectionChanged="Iddetails" Name="dgsample" BorderBrush="Black" BorderThickness="2" AutoGenerateColumns="True" CanUserAddRows="True" CanUserDeleteRows="True" CanUserSortColumns="False"  Margin="200,10,10,75"></DataGrid>

    <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="" VerticalAlignment="Top" Width="100" />
    <TextBox Name="tb2" HorizontalAlignment="Left" Height="20" Margin="60,60,0,0" TextWrapping="NoWrap" Text="" VerticalAlignment="Top" Width="100"/>
    <TextBox Name="tb3" HorizontalAlignment="Left" Height="20" Margin="60,110,0,0" TextWrapping="NoWrap" Text="" 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" />
</Grid>

This is my .CS code

public partial class MainWindow : Window
{
    ObservableCollection<User> Users = new ObservableCollection<User>();
    public MainWindow()
    {
        InitializeComponent();

                    Users.Add(new User() { Id = 101, Name = "leon", Salary = 10 });
                    Users.Add(new User() { Id = 102, Name = "allen", Salary = 20 });
                    Users.Add(new User() { Id = 103, Name = "neon", Salary = 30 });
                    Users.Add(new User() { Id = 104, Name = "xeln", Salary = 40 });
                    Users.Add(new User() { Id = 105, Name = "kalen", Salary = 50 });
                    Users.Add(new User() { Id = 106, Name = "velen", Salary = 60 });

                    dgsample.ItemsSource = Users;

            }

   private void Iddetails(object sender, SelectionChangedEventArgs args)
    {
        int index = dgsample.SelectedIndex;

        tb1.Text = Users[index].Id.ToString();
        tb2.Text = Users[index].Name;
        tb3.Text = Users[index].Salary.ToString();

    }
    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");

    }

    }

This code is working but i need the same thing using the concept of DataBinding and Validations for TextBoxes,Please help me with the required code

user2889489
  • 667
  • 2
  • 9
  • 11
  • In general you can bind a property of a control to property in code-behind/property of other control by for example `Content={Binding Path=content ElementName=name}` – Tafari Oct 22 '13 at 06:39

3 Answers3

2

this may help you

<Binding Path="EventDate"  UpdateSourceTrigger="PropertyChanged">
   <Binding.ValidationRules>
      <ExceptionValidationRule />
   </Binding.ValidationRules>
</Binding>

you can refer to this link also http://www.codeproject.com/Articles/29054/WPF-Data-Binding-Part-1

Debashrita
  • 940
  • 1
  • 8
  • 20
1

What you need to do first ist read about MVVM.

You seem to be using wpf as winforms which sucks big time.

When you done reading about mvvm (let say in a week.. or so), read those articles.

IDataErrorInfo is what you looking for:

http://codeblitz.wordpress.com/2009/05/08/wpf-validation-made-easy-with-idataerrorinfo/

http://tarundotnet.wordpress.com/2011/03/03/wpf-tutorial-how-to-use-idataerrorinfo-in-wpf/

dev hedgehog
  • 8,698
  • 3
  • 28
  • 55
1

Well you would have some work rewriting it using DataBinding that is the general overview on creating data bindings for example:

<TextBox Name="tb3" HorizontalAlignmentText="{Binding Path=SelectedIndex, ElementName=Grid, , Mode=OneWay}"/>

So let me explain, I have binded Text property of TextBox tb3 to the following property SelctedIndex of element Grid using following mode OneWay which means, changing the selected index in the Grid will affect tb3 Text but changing the Text in the textbox will not affect actual Grid selection. Sometimes when the property types doesn't match you have to use a converter here is an example:

msdn.microsoft.com

In general it looks pretty much like this, but note that you could also bind the propierties in code-behind but if you can better stay to xaml.

Tip: If you want to use bindings you have to make sure that the Path points at property.

Finally here are the links for more information about validation you should check out:

NEW: www.codeproject.com

SO question

blogs.msdn.com

Or code-behind (not recommended)

private void tb1_TextChanged(object sender, TextChangedEventArgs e)
{
    int output;
    if (!int.TryParse(tb1.Text, out output))
    {
        MessageBox.Show("Enter valid int.");
        tb1.Text = "0";
    }
}

Useful link about DataBinding:

msdn.microsoft.com

Here I provide you with binding and converter for tb2 TextBox, to display currently selected user name:

Add this class to your namespace:

using System;
using System.Globalization;
using System.Windows.Data;

namespace WpfApplicationTest
{
[ValueConversion(typeof(object), typeof(String))]
public class MyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string name = "";
        if (value != null)
        {
            User user = (User)value;
            name = user.Name;
        }
        else
        {
            name = "";
        }

        return name;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }
}
}

Then add this to you window:

xmlns:myNamespace="clr-namespace:WpfApplicationTest"

<Window.Resources>
    <myNamespace:MyConverter x:Key="myConverter"/>
</Window.Resources>

Then edit your TextBox like this:

<TextBox Name="tb2" Text="{Binding Path=SelectedItem, ElementName=Grid, Mode=OneWay, Converter={StaticResource myConverter}}"/>
Community
  • 1
  • 1
Tafari
  • 2,639
  • 4
  • 20
  • 28
  • @user2889489 I have added some additional code for you, to bind tb2 to currently selected user name. Check my answer for `NEW` link, I think it should be clear enough for you to understand it. If could please upvote my answers as well cheers!. – Tafari Oct 22 '13 at 10:37
  • @user2889489 I have gave you three links use this one for validations in xaml: http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation or make it via code-behind – Tafari Oct 22 '13 at 11:11
  • if u free can u look at this question http://stackoverflow.com/questions/19703655/how-to-hide-and-show-usercontrols-based-on-selecteditem-in-listbox-wpf-mvvm-mode – user2889489 Oct 31 '13 at 10:42
  • @user2889489 well I don't really have time right now, maybe tomorrow if you will still have no accepted answer ; ) – Tafari Oct 31 '13 at 11:27
  • try it when ever u r free – user2889489 Oct 31 '13 at 11:37
  • i have posted all my code pls chck and try to do if possible ,actually i have to finish it by tommorow – user2889489 Oct 31 '13 at 12:54
  • @user2889489 Unfortunately I do not have much time today and there is a lot of code. – Tafari Oct 31 '13 at 13:11