Validating event on datagridview Winform c#

Hi,

I'm using the cellvalidating event on a datagridview.



I’m trying the event but not having much luck.

1.       I can’t seem to get my ValidateTheEntry() function to return a 0 if the entry is either “” or NULL or string.
2.      I only need to validate certain columns in the datagrid, I don’t need to validate the EAN or the description for instance and yet the column index don’t seem to be logical?



private void dgCleanseData_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            //validating cell
            //should only validate certain cells i.e. not the description
            if (e.ColumnIndex == 3 || e.ColumnIndex == 7)
            {
                ValidateTheEntry(e.FormattedValue.ToString());
            }
        }




public int ValidateTheEntry(string number)
        {
            int temp;
            string result;
            if (number != null && !string.IsNullOrEmpty(number))
            {
                if (int.TryParse(number, out temp))
                {
                    result = temp.ToString();
                }
                else
                {
                    result = "0";
                }
            }
            else
            {
                result = "";
            }
            number = result;
            return Convert.ToInt32(result);
        }
SmashAndGrabAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

it_saigeDeveloperCommented:
This works for me:

Form1.cs -
using System;
using System.ComponentModel;
using System.Windows.Forms;

namespace EE_Q28642985
{
	public partial class Form1 : Form
	{
		private BindingList<Employee> employees = new BindingList<Employee>();

		public Form1()
		{
			InitializeComponent();
		}

		private void OnCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
		{
			if (sender is DataGridView)
			{
				DataGridView dgv = sender as DataGridView;
				if (e.ColumnIndex == 3 || e.ColumnIndex == 7)
					dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ValidateEntry((string)e.FormattedValue);
			}
		}

		private int? ValidateEntry(string value)
		{
			int temp;
			int? result;
			if (value != null && !string.IsNullOrEmpty(value))
			{
				if (int.TryParse(value, out temp))
					result = temp;
				else
					result = 0;
			}
			else
				result = null;
			return result;
		}

		private void OnLoad(object sender, EventArgs e)
		{
			for (int i = 0; i < 10; i++)
				employees.Add(new Employee() { ID = i + 1, Name = string.Format("Employee{0}", i + 1), Hired = DateTime.Now.AddDays(i), Hours = i + 40, IsOnVacation = i % 2 == 0, VacationStarted = i % 2 == 0 ? DateTime.Now.AddMonths(i + 1) : DateTime.MinValue, ReturnDate = i % 2 == 0 ? DateTime.Now.AddMonths(i + 1).AddDays(14) : DateTime.MinValue });
			binder.DataSource = employees;
			dgvData.DataSource = binder;
		}
	}

	class Employee
	{
		public int ID { get; set; }
		public string Name { get; set; }
		public DateTime Hired { get; set; }
		public int? Hours { get; set; }
		public bool IsOnVacation { get; set; }
		public DateTime VacationStarted { get; set; }
		public DateTime ReturnDate { get; set; }
		public int? DaysLeft 
		{
			get { return (ReturnDate - VacationStarted).Days; }
			set 
			{
				if (IsOnVacation && value.HasValue && !value.Equals(DaysLeft))
					ReturnDate = ReturnDate.AddDays(-value.Value);
			} 
		}
	}
}

Open in new window

Form1.Designer.cs -
namespace EE_Q28642985
{
	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.components = new System.ComponentModel.Container();
			this.dgvData = new System.Windows.Forms.DataGridView();
			this.binder = new System.Windows.Forms.BindingSource(this.components);
			((System.ComponentModel.ISupportInitialize)(this.dgvData)).BeginInit();
			((System.ComponentModel.ISupportInitialize)(this.binder)).BeginInit();
			this.SuspendLayout();
			// 
			// dgvData
			// 
			this.dgvData.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
					  | System.Windows.Forms.AnchorStyles.Left)
					  | System.Windows.Forms.AnchorStyles.Right)));
			this.dgvData.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
			this.dgvData.Location = new System.Drawing.Point(13, 13);
			this.dgvData.Name = "dgvData";
			this.dgvData.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
			this.dgvData.Size = new System.Drawing.Size(466, 275);
			this.dgvData.TabIndex = 0;
			this.dgvData.CellValidating += new System.Windows.Forms.DataGridViewCellValidatingEventHandler(this.OnCellValidating);
			// 
			// Form1
			// 
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(491, 300);
			this.Controls.Add(this.dgvData);
			this.Name = "Form1";
			this.Text = "Form1";
			this.Load += new System.EventHandler(this.OnLoad);
			((System.ComponentModel.ISupportInitialize)(this.dgvData)).EndInit();
			((System.ComponentModel.ISupportInitialize)(this.binder)).EndInit();
			this.ResumeLayout(false);

		}

		#endregion

		private System.Windows.Forms.DataGridView dgvData;
		private System.Windows.Forms.BindingSource binder;
	}
}

Open in new window

Produces the following output -Initial Load (manually resized the form to show the entire grid)Changing the integer value to 'this old man'Stepping through the code produces a value of 0.Datagrid reflects the change.Choosing a different row for a null/empty check.Debugging shows that null is returned.Datagrid reflects change.-saige-

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.