Validating and correcting the text

4 posts, 0 answers
  1. Lasse
    Lasse avatar
    21 posts
    Member since:
    Jul 2011

    Posted 27 Oct 2011 Link to this post

    Hi,

    Have a grid that mainly presents start and end time for a workshift.
    When I edit this grid, i would like to input '1000' and validate this and correct it to 10:00, or input 130 and validate this and correct it to 01:30. Or 2350 - > 23:50. And if the user inputs 10:20 it should only validate and it should be ok. But if the user inputs 1080, 1667 or 10:98. It should all give an exception while validateing. It should happen when the cursor leaves the cell.

    How can this be done most efficiently. 

    Regards
    Svein Thomas
  2. Martin Vasilev
    Admin
    Martin Vasilev avatar
    1061 posts

    Posted 31 Oct 2011 Link to this post

    Hello Svein,

    Thank you for writing.

    For your requirement you might find useful one of the standard validation events which RadGridView provides. Please find more details in our product documentation.

    Let me know if you have any additional questions.

    Best wishes,
    Martin Vasilev
    the Telerik team

    Q2’11 SP1 of RadControls for WinForms is available for download (see what's new); also available is the Q3'11 Roadmap for Telerik Windows Forms controls.

  3. Lasse
    Lasse avatar
    21 posts
    Member since:
    Jul 2011

    Posted 01 Nov 2011 Link to this post

    Yes, but when I do the validation and try to correct the text, i get an exception..

    Please try the following code:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.Text.RegularExpressions;
    using Telerik.WinControls.UI;
    using System.Globalization;
    using Telerik.WinControls;
     
    namespace WindowsFormsApplication3
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
                SetupDataTable();
            }
     
            DataTable workdayPatternTable = new DataTable();
            private void SetupDataTable()
            {
                System.Globalization.CultureInfo ci = System.Threading.Thread.CurrentThread.CurrentCulture;
     
                workdayPatternTable.Columns.Add("ID", typeof(int));
                workdayPatternTable.Columns.Add("WeekNumber", typeof(int));
                workdayPatternTable.Columns.Add("WeekDay", typeof(int));
                workdayPatternTable.Columns.Add("DayID0", typeof(int));
                workdayPatternTable.Columns.Add("Start0", typeof(DateTime));
                workdayPatternTable.Columns.Add("End0", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break0", typeof(Double));
                workdayPatternTable.Columns.Add("DayID1", typeof(int));
                workdayPatternTable.Columns.Add("Start1", typeof(DateTime));
                workdayPatternTable.Columns.Add("End1", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break1", typeof(Double));
                workdayPatternTable.Columns.Add("DayID2", typeof(int));
                workdayPatternTable.Columns.Add("Start2", typeof(DateTime));
                workdayPatternTable.Columns.Add("End2", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break2", typeof(Double));
                workdayPatternTable.Columns.Add("DayID3", typeof(int));
                workdayPatternTable.Columns.Add("Start3", typeof(DateTime));
                workdayPatternTable.Columns.Add("End3", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break3", typeof(Double));
                workdayPatternTable.Columns.Add("DayID4", typeof(int));
                workdayPatternTable.Columns.Add("Start4", typeof(DateTime));
                workdayPatternTable.Columns.Add("End4", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break4", typeof(Double));
                workdayPatternTable.Columns.Add("DayID5", typeof(int));
                workdayPatternTable.Columns.Add("Start5", typeof(DateTime));
                workdayPatternTable.Columns.Add("End5", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break5", typeof(Double));
                workdayPatternTable.Columns.Add("DayID6", typeof(int));
                workdayPatternTable.Columns.Add("Start6", typeof(DateTime));
                workdayPatternTable.Columns.Add("End6", typeof(DateTime));
                workdayPatternTable.Columns.Add("Break6", typeof(Double));
     
                this.WorkdayPatternGrid.CellFormatting += new Telerik.WinControls.UI.CellFormattingEventHandler(WorkdayPatternGrid_CellFormatting);
                this.WorkdayPatternGrid.CellValidating += new Telerik.WinControls.UI.CellValidatingEventHandler(WorkdayPatternGrid_CellValidating);
                this.WorkdayPatternGrid.EnableCustomDrawing = true;
                this.WorkdayPatternGrid.AutoGenerateColumns = false;
                this.WorkdayPatternGrid.EnableGrouping = false;
                this.WorkdayPatternGrid.AddNewRowPosition = SystemRowPosition.Bottom;
                //this.radGridView1.ReadOnly = true;
                this.WorkdayPatternGrid.DataSource = workdayPatternTable;
                //this.radGridView1.AutoExpandGroups = true;
     
     
                //this.radGridView1.GroupDescriptors.Add(new Telerik.WinControls.Data.GroupDescriptor("Pattern"));
                GridViewTextBoxColumn idcol = new GridViewTextBoxColumn("ID");
                idcol.IsVisible = false;
     
                GridViewTextBoxColumn weekcol = new GridViewTextBoxColumn("WeekNumber");
                weekcol.HeaderText = "WeekNo";
                weekcol.TextAlignment = ContentAlignment.MiddleCenter;
                weekcol.ReadOnly = true;
                weekcol.Width = 38;
     
     
                GridViewImageColumn errcol = new GridViewImageColumn("ErrCol");
                errcol.HeaderText = "";
                errcol.TextAlignment = ContentAlignment.MiddleCenter;
                errcol.ReadOnly = true;
                errcol.Width = 20;
     
     
     
                this.WorkdayPatternGrid.Columns.Add(idcol);
                this.WorkdayPatternGrid.Columns.Add(weekcol);
                this.WorkdayPatternGrid.Columns.Add(errcol);
     
                for (int i = 0; i < 7; i++)
                {
                    GridViewTextBoxColumn dayidcol = new GridViewTextBoxColumn("DayID" + i, "DayID" + i);
                    GridViewTextBoxColumn startcol = new GridViewTextBoxColumn("Start" + i, "Start" + i);
                    GridViewTextBoxColumn endcol = new GridViewTextBoxColumn("End" + i, "End" + i);
                    GridViewTextBoxColumn breakcol = new GridViewTextBoxColumn("Break" + i, "Break" + i);
     
                    dayidcol.IsVisible = false;
     
                    startcol.FormatString = "{0:HH:mm}";
                    startcol.TextAlignment = ContentAlignment.MiddleCenter;
                    startcol.HeaderText = "Start";
                    startcol.Width = 40;
                    //startcol.AutoSizeMode = BestFitColumnMode.HeaderCells;
     
                    endcol.FormatString = "{0:HH:mm}";
                    endcol.TextAlignment = ContentAlignment.MiddleCenter;
                    endcol.HeaderText = "End";
                    endcol.Width = 40;
                    //endcol.AutoSizeMode = BestFitColumnMode.HeaderCells;
     
                    breakcol.TextAlignment = ContentAlignment.MiddleCenter;
                    breakcol.HeaderText = "Break";
                    breakcol.Width = 35;
                    //breakcol.AutoSizeMode = BestFitColumnMode.HeaderCells;
     
                    this.WorkdayPatternGrid.Columns.Add(dayidcol);
                    this.WorkdayPatternGrid.Columns.Add(startcol);
                    this.WorkdayPatternGrid.Columns.Add(endcol);
                    this.WorkdayPatternGrid.Columns.Add(breakcol);
                }
     
                ColumnGroupsViewDefinition def = new ColumnGroupsViewDefinition();
     
                def.ColumnGroups.Add(new GridViewColumnGroup("Event"));
                def.ColumnGroups[0].ShowHeader = false;
                def.ColumnGroups[0].Rows.Add(new GridViewColumnGroupRow());
                def.ColumnGroups[0].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns[0]);
                def.ColumnGroups[0].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns[1]);
     
                for (int i = 0; i < 7; i++)
                {
     
                    def.ColumnGroups.Add(new GridViewColumnGroup(ci.DateTimeFormat.DayNames.ToList()[i]));
                    def.ColumnGroups[1 + i].Rows.Add(new GridViewColumnGroupRow());
                    def.ColumnGroups[1 + i].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns["DayID" + i]);
                    def.ColumnGroups[1 + i].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns["Start" + i]);
                    def.ColumnGroups[1 + i].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns["End" + i]);
                    def.ColumnGroups[1 + i].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns["Break" + i]);
                }
     
                var fdow = (int)ci.DateTimeFormat.FirstDayOfWeek;
                for (int i = 0; i < fdow; i++)
                {
                    def.ColumnGroups.Move(1 + i, def.ColumnGroups.Count() - 1);
                }
     
                def.ColumnGroups.Add(new GridViewColumnGroup("Errors"));
                def.ColumnGroups[8].ShowHeader = false;
                def.ColumnGroups[8].Rows.Add(new GridViewColumnGroupRow());
                def.ColumnGroups[8].Rows[0].Columns.Add(this.WorkdayPatternGrid.Columns[2]);
     
     
                this.WorkdayPatternGrid.ViewDefinition = def;
                //this.radGridView1.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill;
     
            }
     
            void WorkdayPatternGrid_CellValidating(object sender, Telerik.WinControls.UI.CellValidatingEventArgs e)
            {
     
                if (e.Column.Name.StartsWith("Start") || e.Column.Name.StartsWith("End"))
                {
                    string timeValue = e.Value.ToString();
                    if (!IsTime(timeValue))
                    {
                        if (timeValue.Length == 4)
                            timeValue = timeValue.Insert(2, ":");
                        if (!IsTime(timeValue))
                            e.Cancel = true;
                        else
                            e.ActiveEditor.Value = timeValue;
                    }
     
                }
            }
     
            void WorkdayPatternGrid_CellFormatting(object sender, Telerik.WinControls.UI.CellFormattingEventArgs e)
            {
                GridDataCellElement cell = e.CellElement as GridDataCellElement;
                if (cell != null)
                {
                    if (cell.ContainsErrors)
                    {
                        cell.DrawBorder = true;
                        cell.BorderBoxStyle = BorderBoxStyle.SingleBorder;
                        cell.BorderWidth = 2;
                        cell.BorderColor = Color.Red;
                    }
                    else
                    {
                        cell.ResetValue(LightVisualElement.DrawBorderProperty, ValueResetFlags.Local);
                        cell.ResetValue(LightVisualElement.BorderBoxStyleProperty, ValueResetFlags.Local);
                        cell.ResetValue(LightVisualElement.BorderWidthProperty, ValueResetFlags.Local);
                        cell.ResetValue(LightVisualElement.BorderColorProperty, ValueResetFlags.Local);
                    }
                }
            }
     
            bool IsTime(string time)
            {
                Match match = Regex.Match(time, "(([0-1][0-9])|([2][0-3])):([0-5][0-9])");
                if (match.Success)
                    return true;
     
                return false;
            }
     
     
            public int GetWeekNumber(DateTime dtPassed)
            {
                CultureInfo ciCurr = CultureInfo.CurrentCulture;
                int weekNum = ciCurr.Calendar.GetWeekOfYear(dtPassed, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
                return weekNum;
            }
            private void AddRow(DataTable table, int rowID, DateTime start, DateTime end, Double breakTime)
            {
                var dow = (int)start.DayOfWeek;
                var w = GetWeekNumber(start);
     
                DataRow[] rows = table.Select("WeekNumber = " + w.ToString());
                DataRow row = null;
                if (rows.Count() == 0)
                    row = table.Rows.Add(rowID, w, dow);
                else
                    row = rows[0];
     
                row["DayID" + dow] = rowID;
                row["Start" + dow] = start;
                row["End" + dow] = end;
                row["Break" + dow] = breakTime;
     
     
            }
     
            private GridDataCellElement GetCell(GridRowElement rowElement, int index)
            {
                foreach (GridCellElement cell in rowElement.VisualCells)
                {
                    if (cell.ColumnInfo != null && cell.ColumnInfo.Index == index)
                    {
                        return cell as GridDataCellElement;
                    }
                }
                return null;
            }
     
     
     
            protected override void OnLoad(EventArgs e)
            {
                AddRow(workdayPatternTable, 1, new DateTime(1900, 01, 01, 07, 30, 00), new DateTime(1900, 01, 01, 15, 30, 00), .5);
                AddRow(workdayPatternTable, 2, new DateTime(1900, 01, 02, 14, 30, 00), new DateTime(1900, 01, 02, 22, 30, 00), .5);
                AddRow(workdayPatternTable, 3, new DateTime(1900, 01, 04, 22, 00, 00), new DateTime(1900, 01, 05, 07, 30, 00), .5);
                AddRow(workdayPatternTable, 4, new DateTime(1900, 01, 05, 22, 00, 00), new DateTime(1900, 01, 06, 07, 30, 00), .5);
                AddRow(workdayPatternTable, 5, new DateTime(1900, 01, 08, 07, 30, 00), new DateTime(1900, 01, 08, 15, 30, 00), .5);
                AddRow(workdayPatternTable, 6, new DateTime(1900, 01, 09, 07, 30, 00), new DateTime(1900, 01, 09, 15, 30, 00), .5);
                AddRow(workdayPatternTable, 7, new DateTime(1900, 01, 11, 14, 30, 00), new DateTime(1900, 01, 11, 22, 30, 00), .5);
                AddRow(workdayPatternTable, 8, new DateTime(1900, 01, 12, 07, 30, 00), new DateTime(1900, 01, 12, 15, 30, 00), .5);
                AddRow(workdayPatternTable, 9, new DateTime(1900, 01, 16, 07, 30, 00), new DateTime(1900, 01, 16, 22, 30, 00), .5);
     
            }
        }
    }

    namespace WindowsFormsApplication3
    {
        partial class Form1
        {
            /// <summary>
            /// Required designer variable.
            /// </summary>
            private System.ComponentModel.IContainer components = null;
     
            /// <summary>
            /// Clean up any resources being used.
            /// </summary>
            /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
     
            #region Windows Form Designer generated code
     
            /// <summary>
            /// Required method for Designer support - do not modify
            /// the contents of this method with the code editor.
            /// </summary>
            private void InitializeComponent()
            {
                this.WorkdayPatternGrid = new Telerik.WinControls.UI.RadGridView();
                ((System.ComponentModel.ISupportInitialize)(this.WorkdayPatternGrid)).BeginInit();
                this.SuspendLayout();
                //
                // WorkdayPatternGrid
                //
                this.WorkdayPatternGrid.Location = new System.Drawing.Point(55, 49);
                this.WorkdayPatternGrid.Name = "WorkdayPatternGrid";
                this.WorkdayPatternGrid.Size = new System.Drawing.Size(527, 227);
                this.WorkdayPatternGrid.TabIndex = 0;
                this.WorkdayPatternGrid.Text = "radGridView1";
                //
                // Form1
                //
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(646, 418);
                this.Controls.Add(this.WorkdayPatternGrid);
                this.Name = "Form1";
                this.Text = "Form1";
                ((System.ComponentModel.ISupportInitialize)(this.WorkdayPatternGrid)).EndInit();
                this.ResumeLayout(false);
     
            }
     
            #endregion
     
            private Telerik.WinControls.UI.RadGridView WorkdayPatternGrid;
        }
    }
  4. Jack
    Admin
    Jack avatar
    2333 posts

    Posted 03 Nov 2011 Link to this post

    Hello Svein Thomas,

    Thank you for contacting us. 

    The described exception occurs, because you are using a text editor and your column's data type is DateTime. You can solve the issue by using a type converter. Here is a sample:
    foreach (GridViewDataColumn column in this.WorkdayPatternGrid.Columns)
    {
        column.DataTypeConverter = new DateConverter();
    }
     
    public class DateConverter: TypeConverter
    {
        public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
        {
            return destinationType == typeof(DateTime);
        }
     
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            if (value is string)
            {
                string[] textValue = ((string)value).Split(':');
                DateTime date = DateTime.Now;
                return new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, int.Parse(textValue[0]), int.Parse(textValue[1]), 0);
            }
     
            if (value is DateTime && destinationType == typeof(DateTime))
            {
                return value;
            }
     
            return base.ConvertTo(context, culture, value, destinationType);
        }
     
        public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
        {
            return sourceType == typeof(DateTime);
        }
     
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            DateTime dateValue = (DateTime)value;
            return "" + dateValue.Hour.ToString() + ":" + dateValue.Minute.ToString();
        }
    }

    Find more about data conversion from the following help article. There is also an example in our demo application: GridView >> Manipulate data >> Convert values.

    I hope this helps.
     
    Kind regards,
    Jack
    the Telerik team

    Q2’11 SP1 of RadControls for WinForms is available for download (see what's new); also available is the Q3'11 Roadmap for Telerik Windows Forms controls.

Back to Top