C#でDataGridViewの列にNumericUpDownにしたくカスタマイズを行っています。
http://msdn.microsoft.com/ja-jp/library/7tas5c80(VS.80).aspx
こちらのサイトを参考にし以下のソースになりました。
public class NumericUpDownColumn : DataGridViewColumn
{
public NumericUpDownColumn()
: base(new NumericUpDownCell())
{
}
public override DataGridViewCell CellTemplate
{
get
{
return base.CellTemplate;
}
set
{
base.CellTemplate = value;
}
}
}
public class NumericUpDownCell : DataGridViewTextBoxCell
{
public override void InitializeEditingControl(int rowIndex, object
initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
{
base.InitializeEditingControl(rowIndex, initialFormattedValue,
dataGridViewCellStyle);
NumericUpDownCellEditingControl ctl =
DataGridView.EditingControl as NumericUpDownCellEditingControl;
if (this.Value != null) ctl.Value = decimal.Parse(this.Value.ToString());
}
public override Type EditType
{
get
{
return typeof(NumericUpDownCellEditingControl);
}
}
public override Type ValueType
{
get
{
return typeof(decimal);
}
}
public override object DefaultNewRowValue
{
get
{
return (decimal)0;
}
}
}
class NumericUpDownCellEditingControl : NumericUpDown, IDataGridViewEditingControl
{
DataGridView dataGridView;
private bool valueChanged = false;
int rowIndex;
public object EditingControlFormattedValue
{
get
{
return this.Value;
}
set
{
String newValue = value as String;
if (newValue != null)
{
this.Value = decimal.Parse(newValue);
}
}
}
public object GetEditingControlFormattedValue(
DataGridViewDataErrorContexts context)
{
return EditingControlFormattedValue;
}
public void ApplyCellStyleToEditingControl(
DataGridViewCellStyle dataGridViewCellStyle)
{
this.Font = dataGridViewCellStyle.Font;
}
public int EditingControlRowIndex
{
get
{
return rowIndex;
}
set
{
rowIndex = value;
}
}
public bool EditingControlWantsInputKey(
Keys key, bool dataGridViewWantsInputKey)
{
switch (key & Keys.KeyCode)
{
case Keys.Left:
case Keys.Up:
case Keys.Down:
case Keys.Right:
return true;
default:
return false;
}
}
public bool RepositionEditingControlOnValueChange
{
get
{
return false;
}
}
public DataGridView EditingControlDataGridView
{
get
{
return dataGridView;
}
set
{
dataGridView = value;
}
}
public bool EditingControlValueChanged
{
get
{
return valueChanged;
}
set
{
valueChanged = value;
}
}
public Cursor EditingPanelCursor
{
get
{
return base.Cursor;
}
}
protected override void OnValueChanged(EventArgs eventargs)
{
valueChanged = true;
this.EditingControlDataGridView.NotifyCurrentCellDirty(true);
base.OnValueChanged(eventargs);
}
}
}
デザイン画面で列を追加し実行。グリッド上のNumericUpDownで数値を変更し
違うセルを選択すると「セルのフォーマットされた値に間違った型が指定されていますと例外がでます。場所はDataGridViewCellのParseFormattedValueでした。
どのようにすれば例外がでなくなるでしょうか。ちょっと文字数の関係上色々はしょってしまってます。
よろしくお願いします。