DataGridView中自定义NumericUpDown控件的问题 [英] Problem with custom NumericUpDown control in DataGridView

查看:78
本文介绍了DataGridView中自定义NumericUpDown控件的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>>尝试发布之前它似乎挂了。请原谅如果这是双重帖子>>>



我有一个带有三个自定义列控件的DataGridView。一个是日期选择器,我在网上找到的代码是
。我修改了它给我一个仅限时间的日期选择器。我发现有人采用了相同的代码并对其进行了修改,以便为DataGridViews生成NumericUpDown旋转控件。我正在使用这个自定义的NumericUpDown控件,除了一个功能外它工作得很好 - 当它显示的数据的初始值为零时,它不会显示零。它显示所有其他初始值,但将单元格留空为零。



我的问题是如何显示零的初始值?



以下是代码。只需将其添加到项目中,根据需要更改命名空间,然后在任何DataGridView列中为ColumnType选择NumericUpDownColumn。



我碰巧使用对象的ArrayList作为我的数据源到网格(通过BindingSource),但任何数据源都应该表现出行为。



  using  Microsoft.VisualBasic; 
使用系统;
使用 System.Collections;
使用 System.Collections.Generic;
使用 System.Data;
使用 System.Diagnostics;
使用 System.Windows.Forms;

// 原始代码直接从以下位置复制:
// http://www.experts-exchange.com/Microsoft/Development/Microsoft_Programming/WPF_and_Silverlight/Q_24582172.html
//
// 我修改了格式以显示整数值而不是十进制,并修复了一些注释(代码显然是从其他地方复制的,
// 带有引用Calendar类的原始注释。除此之外,它按原样工作。

命名空间 EpiModule
{
/// < 摘要 >
/// 一个专门用于DataGridView的spinner(NumericUpDown)类,范围从0到120.
/// < / summary >
public class NumericUpDownColumn:DataGridViewColumn
{
public NumericUpDownColumn(): base new NumericUpDownCell())
{
}

public NumericUpDownColumn(DataGridViewCell单元格)
base (单元格)
{
}

public 覆盖 DataGridViewCell CellTemplate
{
get { return base .CellTemplate; }

set {
// 确保用于模板的单元格是NumericUpDownCell。
if (( value != null )&&!value.GetType()。IsAssignableFrom( typeof (NumericUpDownCell)))
{
throw new InvalidCastException(< span class =code-string> 必须是NumericUpDownCell);
}
base .CellTemplate = value ;
}
}
}

/// < 摘要 >
/// NumericUpDownColumn的辅助类,用于执行单元格编辑。
/// < / summary >
public class NumericUpDownCell:DataGridViewTextBoxCell
{
public NumericUpDownCell( )
{
this .Style.Format = ;
}

public 覆盖 void InitializeEditingControl( int rowIndex, object initialFormattedValue,DataGridViewCellStyle dataGridViewCellStyle)
{
// 将编辑控件的值设置为当前单元格值。
base .InitializeEditingControl(rowIndex,initialFormattedValue,dataGridViewCellStyle);
NumericUpDownEditingControl ctl =(NumericUpDownEditingControl)DataGridView.EditingControl;
ctl.Value = Convert.ToDecimal( this .Value);
}

public 覆盖类型EditType
{
// 返回NumericUpDownCell使用的编辑控件的类型。
< span class =code-keyword> get
{ return typeof (NumericUpDownEditingControl); }
}

public 覆盖类型ValueType
{
// 返回NumericUpDownCell包含的值的类型。
< span class =code-keyword> get { return typeof INT ); }
}

public 覆盖 object DefaultNewRowValue
{
// 新的默认值在网格中添加了行
get { return 0 ; }
}
}

/// < 摘要 >
/// NumericUpDownColumn的辅助类,为正常的NumericUpDown控件提供适当的重写接口。
/// < / summary >
class NumericUpDownEditingControl:NumericUpDown,IDataGridViewEditingControl
{
private DataGridView dataGridViewControl;
private bool valueIsChanged = false ;
private int rowIndexNum;
protected bool initializing = false ;

public NumericUpDownEditingControl()
{
initializing = true ;

this .Minimum =( decimal 0 ;
this .DecimalPlaces = 0 ;
.Maximum = 120 ;

initializing = false ;
}

虚拟 public object EditingControlFormattedValue
{
get { return < span class =code-keyword> this
.Value.ToString( ); }

set
{
if (< span class =code-sdkkeyword> value
int
{
this .Value = int .Parse(Value.ToString());
}
其他 如果 decimal
{
this .Value = decimal .Parse( value .ToString() );
}
}
}

虚拟 public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
{
return this .Value.ToString( );
}

public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
{
this .Font = dataGridViewCellStyle.Font;
this .ForeColor = dataGridViewCellStyle.ForeColor;
this .BackColor = dataGridViewCellStyle.BackColor;
}

public int EditingControlRowIndex
{
get { return rowIndexNum; }
set {rowIndexNum = value ; }
}

public bool EditingControlWantsInputKey(Keys key,< span class =code-keyword> bool
dataGridViewWantsInputKey)
{
// 让DateTimePicker处理列出的键。
switch (key& Keys.KeyCode)
{
< span class =code-keyword> case
Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Right:
case Keys.Home:
case Keys.End:
case Keys.PageDown:
case Keys.PageUp:
return ;
默认
返回 false ;
}
}

public void PrepareEditingControlForEdit( bool selectAll)
{
// 无需做任何准备。
}

public bool RepositionEditingControlOnValueChange
{
get { return ; }
}

public DataGridView EditingControlDataGridView
{
get { return dataGridViewControl; }
set {dataGridViewControl = value ; }
}

public bool EditingControlValueChanged
{
get { return valueIsChanged; }
set {valueIsChanged = value ; }
}

public System.Windows.Forms.Cursor EditingControlCursor
{
获取 {返回 base .Cursor; }
}

System.Windows.Forms.Cursor IDataGridViewEditingControl.EditingPanelCursor
{
get {< span class =code-keyword> return
EditingControlCursor; }
}

受保护 覆盖 void OnValueChanged(EventArgs eventargs)
{
if (!initializing) // 原始代码在没有此内容的情况下爆炸
{
// 通知DataGridView单元格的内容已更改。
valueIsChanged = true ;
this .EditingControlDataGridView.NotifyCurrentCellDirty( true ); base .OnValueChanged(eventargs);
}
}
}

解决方案

问题在于格式化



  //  而不是#应该放0  
return this .Value.ToString( );





转到这个链接 - 它会帮助你。



自定义数字格式字符串 [ ^


>>>Tried to post this before and it seemed to hang. Pardon if this is a double post>>>

I have a DataGridView with three custom column controls. One is for a date picker, the code for which I
found online. I modified that to give me a time-only date picker. I found that someone had taken the same code and modified it to produce a NumericUpDown spin control for DataGridViews. I''m using this custom NumericUpDown control and it works great except for one feature - when the initial value of the data it displays is zero, it will not display the zero. It displays all other initial values, but leaves the cell blank for a zero.

My question is how to get the initial value of zero to display?

Below is the code. Just add it to your project, change the namespace if you wish, and then pick NumericUpDownColumn for ColumnType in any DataGridView column.

I happen to be using an ArrayList of objects as my DataSource to the grid (via a BindingSource), but any data source should exhibit the behavior.

using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Windows.Forms;

// The original code was copied directly from:
//		http://www.experts-exchange.com/Microsoft/Development/Microsoft_Programming/WPF_and_Silverlight/Q_24582172.html
//
// I modified the format to display integer values instead of decimal, and fixed a few comments (the code had obviously been copied from somewhere else,
// with original comments in place referring to a Calendar class). Other than that, it works as is.

namespace EpiModule
{
	/// <summary>
	/// A spinner (NumericUpDown) class specifically for use in a DataGridView, with a range from 0 - 120.
	/// </summary>
	public class NumericUpDownColumn : DataGridViewColumn
	{ 
		public NumericUpDownColumn() : base(new NumericUpDownCell())
		{
		}

		public NumericUpDownColumn(DataGridViewCell cell)
			: base(cell)
		{
		}

		public override DataGridViewCell CellTemplate
		{
			get { return base.CellTemplate; }
			
			set {
					// Ensure that the cell used for the template is a NumericUpDownCell.
				if ((value != null) && !value.GetType().IsAssignableFrom(typeof(NumericUpDownCell)))
				{
					throw new InvalidCastException("Must be a NumericUpDownCell");
				}
				base.CellTemplate = value;
			}
		}
	}

	/// <summary>
	/// An auxilary class to NumericUpDownColumn that carries out the cell editing.
	/// </summary>
	public class NumericUpDownCell : DataGridViewTextBoxCell
	{
		public NumericUpDownCell()
		{
			this.Style.Format = "#";
		}
		
		public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
		{
			// Set the value of the editing control to the current cell value.
			base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
			NumericUpDownEditingControl ctl = (NumericUpDownEditingControl)DataGridView.EditingControl;
			ctl.Value = Convert.ToDecimal(this.Value);
		}
		
		public override Type EditType
		{
			// Return the type of the editing contol that NumericUpDownCell uses.
			get { return typeof(NumericUpDownEditingControl); }
		}
		
		public override Type ValueType
		{
			// Return the type of the value that NumericUpDownCell contains.
			get { return typeof(int); }
		}
		
		public override object DefaultNewRowValue
		{
			// Default value for a newly added row in the grid
			get { return 0; }
		}
	}

	/// <summary>
	/// An auxilary class to NumericUpDownColumn that supplies the appropriate overridden interfaces to the normal NumericUpDown control.
	/// </summary>
	class NumericUpDownEditingControl : NumericUpDown, IDataGridViewEditingControl
	{
		private DataGridView dataGridViewControl;
		private bool valueIsChanged = false;
		private int rowIndexNum;
		protected bool initializing = false;

		public NumericUpDownEditingControl()
		{
			initializing = true;

			this.Minimum = (decimal)0;
			this.DecimalPlaces = 0;
			this.Maximum = 120;

			initializing = false;
		}
		
		virtual public object EditingControlFormattedValue
		{
			get { return this.Value.ToString("#"); }
			
			set
			{
				if (value is int)
				{
					this.Value = int.Parse(Value.ToString());
				}
				else if (value is decimal)
				{
					this.Value = decimal.Parse(value.ToString());
				}
			}
		}
		
		virtual public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
		{
			return this.Value.ToString("#");
		}
		
		public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
		{
			this.Font = dataGridViewCellStyle.Font;
			this.ForeColor = dataGridViewCellStyle.ForeColor;
			this.BackColor = dataGridViewCellStyle.BackColor;
		}
		
		public int EditingControlRowIndex
		{
			get { return rowIndexNum; }
			set { rowIndexNum = value; }
		}
		
		public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
		{
			// Let the DateTimePicker handle the keys listed.
			switch (key & Keys.KeyCode)
			{
				case Keys.Left:
				case Keys.Up:
				case Keys.Down:
				case Keys.Right:
				case Keys.Home:
				case Keys.End:
				case Keys.PageDown:
				case Keys.PageUp:
				return true;
				default:
					return false;
			}
		}
		
		public void PrepareEditingControlForEdit(bool selectAll)
		{
			// No preparation needs to be done.
		}
		
		public bool RepositionEditingControlOnValueChange
		{
			get { return false; }
		}
		
		public DataGridView EditingControlDataGridView
		{
			get { return dataGridViewControl; }
			set { dataGridViewControl = value; }
		}
		
		public bool EditingControlValueChanged
		{
			get { return valueIsChanged; }
			set { valueIsChanged = value; }
		}
		
		public System.Windows.Forms.Cursor EditingControlCursor
		{
			get { return base.Cursor; }
		}
		
		System.Windows.Forms.Cursor IDataGridViewEditingControl.EditingPanelCursor
		{
			get { return EditingControlCursor; }
		}
		
		protected override void OnValueChanged(EventArgs eventargs)
		{
			if (!initializing) // Original code blew up without this
			{
				// Notify the DataGridView that the contents of the cell have changed.
				valueIsChanged = true;
				this.EditingControlDataGridView.NotifyCurrentCellDirty(true);				base.OnValueChanged(eventargs);
			}
		}
	}

解决方案

The problem is in formatting

// instead of # you should put 0
return this.Value.ToString("#");



go to this link - it will help you.

Custom Numeric Format Strings[^]


这篇关于DataGridView中自定义NumericUpDown控件的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆