using System;
using System.Linq;
using System.Windows.Controls;

using C1.Silverlight.Data;

namespace C1Data_Validation
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
            DataTable dt = new DataTable();
            dt.Columns.Add("ID", typeof(int));
            dt.Columns.Add("Title", typeof(string));
            dt.Columns.Add("Description", typeof(string));
            dt.Columns.Add("Product", typeof(string));
            dt.Columns.Add("ActivatedDate", typeof(DateTime));
            dt.Columns.Add("Priority", typeof(Int32));

            dt.ColumnChanging += new DataColumnChangeEventHandler(dt_ColumnChanging);

            string[] Products = new string[] { "WinForm", "WebForm", "WPF", "Silverlight", "iPhone", "Android", "HTML5" };

            for (int i = 1; i < 123; i++)
                dt.Rows.Add(i, "Issue " + i, "", Products[i % Products.Count()], new DateTime(2012, 3, 19 + (i % 10)));

            DataContext = dt.DefaultView;
        }

        // implements custom validation logic
        void dt_ColumnChanging(object sender, DataColumnChangeEventArgs e)
        {
            switch (e.Column.ColumnName)
            {
                case "Priority":
                    // The 'Priority' column should only contain numbers from 1 to 9
                    if (e.ProposedValue == null || ((int)e.ProposedValue > 0 && (int)e.ProposedValue <= 9))
                    {
                        // Clear column error
                        e.Row.SetColumnError(e.Column, null); 
                    }
                    else
                    {
                        // Set column error
                        e.Row.SetColumnError(e.Column, "the value should be from 1 to 9"); 
                    }
                    break;
                case "Title":
                    // The 'Title' column should contain strings not longer than 25 symbols
                    string str = (string)e.ProposedValue;
                    if (string.IsNullOrEmpty(str) || str.Length < 25)
                    {
                        // Clear column error
                        e.Row.SetColumnError(e.Column, null);
                    }
                    else
                    {
                        // Set column error
                        e.Row.SetColumnError(e.Column, "the title should not be longer than 25 symbols");
                    }
                    break;
                default:
                    break;
            }

            // Set RowError text if there are errors in some columns
            if (e.Row.GetColumnsInError().Length > 0)
            {
                // Set row error
                e.Row.RowError = "Please, fix the row errors";
            }
            else
            {
                // Clear row error
                e.Row.RowError = "";
            }
        }

    }
}
