?
Solved

Validating Date and Time inside Datagridview in C#

Posted on 2016-10-06
4
Medium Priority
?
54 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 34

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 34

Accepted Solution

by:
it_saige earned 2000 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

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: Ivo
C# And Nullable Types Since 2.0 C# has Nullable(T) Generic Structure. The idea behind is to allow value type objects to have null values just like reference types have. This concerns scenarios where not all data sources have values (like a databa…
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

752 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