Solved

Validating Date and Time inside Datagridview in C#

Posted on 2016-10-06
4
15 Views
Last Modified: 2016-11-28
Dear Sir/Madam,

Please be kind enough tell me how I can validate Date and Time in datagridview as I enter the data.

Any help would be greatly appreciated.

Kind Regards,
Indunil Sanjeewa
0
Comment
  • 2
4 Comments
 
LVL 32

Expert Comment

by:it_saige
ID: 41832024
Just to clarify, do you mean as you enter data into a text field that is part of the datagridview row you want to validate it?  Or, do you mean that as you insert rows, you want to validate the cell value associated with the column that contains the date time value?

-saige-
0
 

Author Comment

by:Indunil Sanjeewa Amarasinghe
ID: 41832071
I basically need to have a time picker and a date picker in two columns separately not both time and date.

Kind Regards,
Indunil Sanjeewa
0
 
LVL 32

Accepted Solution

by:
it_saige earned 500 total points
ID: 41832501
You could try something like this:

Form1.cs -
using System;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;

namespace EE_Q28974717
{
	public partial class Form1 : Form
	{
		bool IsSendingKeys = false;

		public Form1()
		{
			InitializeComponent();
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			switch (keyData & Keys.KeyCode)
			{
				case Keys.Enter:
				case Keys.Tab:
					dataGridView1.Focus();
					break;
			}
			return base.ProcessCmdKey(ref msg, keyData);
		}

		private void OnLoad(object sender, EventArgs e)
		{
			dataGridView1.DataSource = (from i in Enumerable.Range(0, 10) select new { ID = i, FirstName = string.Format("FirstName{0}", i), StartDate = DateTime.MinValue, StartTime = DateTime.MinValue, EndDate = DateTime.MinValue, EndTime = DateTime.MinValue }).ToList();
		}

		private void OnCellClick(object sender, DataGridViewCellEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				if (grid.Rows.Count > 0)
				{
					var dtp = default(DateTimePicker);
					var columns = new[] { "startdate", "starttime", "enddate", "endtime" };
					var column = grid.Columns[e.ColumnIndex].Name;
					if (columns.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase)))
					{
						dtp = new DateTimePicker();
						grid.Controls.Add(dtp);
						dtp.Format = column.IndexOf("time", StringComparison.OrdinalIgnoreCase) > -1 ? DateTimePickerFormat.Time : DateTimePickerFormat.Short;
						if (dtp.Format.Equals(DateTimePickerFormat.Time))
							dtp.ShowUpDown = true;
						var rectangle = grid.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true);
						dtp.Size = new Size(rectangle.Width, rectangle.Height);
						dtp.Location = new Point(rectangle.X, rectangle.Y);
						//dtp.CloseUp += OnCloseUp;
						dtp.Leave += OnLeave;
						dtp.Validating += OnValidating;
						dtp.Visible = true;
					}
				}
			}
		}

		private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
		{
			if (sender is DataGridView)
			{
				var grid = sender as DataGridView;
				if (grid.Rows.Count > 0)
				{
					var columns = new[] { "startdate", "starttime", "enddate", "endtime" };
					var column = grid.Columns[e.ColumnIndex].Name;
					if (columns.Any(x => x.Equals(column, StringComparison.OrdinalIgnoreCase)))
						e.Value = ((DateTime)e.Value).ToString(column.IndexOf("time", StringComparison.OrdinalIgnoreCase) > -1 ? "hh:mm tt" : "MM/dd/yyyy");
				}
			}
		}

		private void OnLeave(object sender, EventArgs e)
		{
			if (sender is DateTimePicker)
			{
				var dtp = sender as DateTimePicker;
				if (dtp != null && !string.IsNullOrEmpty(dtp.Text))
				{
					try
					{
						IsSendingKeys = true;
						SendKeys.SendWait("{RIGHT}");
						SendKeys.SendWait("{LEFT}");
					}
					finally
					{
						IsSendingKeys = false;
					}
				}
				dtp.Visible = false;
			}
		}

		private void OnValidating(object sender, EventArgs e)
		{
			if (sender is DateTimePicker)
			{
				var dtp = sender as DateTimePicker;
				var grid = dtp.Parent as DataGridView;
				if (grid.Rows.Count > 0)
				{
					var row = grid.Rows[grid.CurrentCell.RowIndex];
					if (row.DataBoundItem != null)
					{
						var data = row.DataBoundItem.Cast(new { ID = -1, FirstName = "", StartDate = DateTime.MinValue, StartTime = DateTime.MinValue, EndDate = DateTime.MinValue, EndTime = DateTime.MinValue });
						var flags = BindingFlags.NonPublic | BindingFlags.Instance;
						var formats = new[] { "<{0}>i__Field", "<{0}>" };
						foreach (var property in data.GetType().GetProperties())
						{
							if (property.Name.Equals(grid.Columns[grid.CurrentCell.ColumnIndex].Name, StringComparison.OrdinalIgnoreCase))
							{
								var names = formats.Select(x => string.Format(x, property.Name)).ToList();
								var field = data.GetType().GetFields(flags).First(f => names.Contains(f.Name));
								if (field != null)
									field.SetValue(data, dtp.Value);
							}
						}
					}
				}
				dtp.Visible = false;
			}
		}
	}

	static class Extensions
	{
		public static T Cast<T>(this object obj, T type)
		{
			return (T)obj;
		}
	}
}

Open in new window

Form1.Desinger.cs -
namespace EE_Q28974717
{
	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.dataGridView1 = new System.Windows.Forms.DataGridView();
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit();
			this.SuspendLayout();
			// 
			// dataGridView1
			// 
			this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dataGridView1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.dataGridView1.Location = new System.Drawing.Point(0, 0);
			this.dataGridView1.Name = "dataGridView1";
			this.dataGridView1.Size = new System.Drawing.Size(531, 290);
			this.dataGridView1.TabIndex = 0;
			this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.OnCellClick);
			this.dataGridView1.CellFormatting += new System.Windows.Forms.DataGridViewCellFormattingEventHandler(this.OnCellFormatting);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(531, 290);
			this.Controls.Add(this.dataGridView1);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit();
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.DataGridView dataGridView1;
	}
}

Open in new window

Which produces the following output -

Initial load:Capture.JPGChanging the start date:Capture.JPGTabbing to the next column after the change:Capture.JPGChanging the start time:Capture.JPGTabbing to the next column after the change:Capture.JPG
-saige-
2
 
LVL 13

Expert Comment

by:frankhelk
ID: 41903872
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I have recommended this question be closed as follows:

Accept: it_saige (https:#a41832501)

If you feel this question should be closed differently, post an objection and the moderators will review all objections and close it as they feel fit. If no one objects, this question will be closed automatically the way described above.

frankhelk
Experts-Exchange Cleanup Volunteer
0

Featured Post

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
When you create an app prototype with Adobe XD, you can insert system screens -- sharing or Control Center, for example -- with just a few clicks. This video shows you how. You can take the full course on Experts Exchange at http://bit.ly/XDcourse.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now