Solved

Validating Date and Time inside Datagridview in C#

Posted on 2016-10-06
4
35 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 33

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 33

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 14

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Extention Methods in C# 3.0 by Ivo Stoykov C# 3.0 offers extension methods. They allow extending existing classes without changing the class's source code or relying on inheritance. These are static methods invoked as instance method. This…
This article aims to explain the working of CircularLogArchiver. This tool was designed to solve the buildup of log file in cases where systems do not support circular logging or where circular logging is not enabled
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

713 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