2017-08-02 69 views
0

我有一個功能,只限制我的datagridview(行ID)的第一列是一個數字。但是,當我點擊第一列時,它不僅限制了我的第一列,而且還限制了整個datagridview只輸入數字。以下是我的代碼。只允許來自datagridview的列只能插入數字

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    if (dataGridView1.CurrentCell.ColumnIndex == 0) 
    { 
     e.Control.KeyPress += new KeyPressEventHandler(Column1_KeyPress); 
    } 
} 

private void Column1_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && e.KeyChar != '.') 
    { 
     e.Handled = true; 
    } 

    if (e.KeyChar == '.' && (sender as TextBox).Text.IndexOf('.') > -1) 
    { 
     e.Handled = true; 
    } 
} 

回答

0

我這樣做的方式是將一個NumericUpDown控件分配給datagrid視圖。但是你必須將其作爲自定義列來完成。如果你願意,你可以使用相同的概念進行其他類型的控制。

您需要

  • 數字列
  • 數字單元控制
  • 數字向上向下細胞

NumericColumn在您的datagridview分配。 列包含NumericCellControl 這包含編輯

下面一個NumericUpDownCell是我使用的代碼,有些情況定製我的要求,所以你必須相應地更新。例如,我有固定的最小值,最大值和默認值1.0。

NumericUpDownCell

class NumericUpDownCell: DataGridViewTextBoxCell 
{ 
    public NumericUpDownCell(): base() 
    { 
     this.Style.Format = "0.0"; 
    } 

    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); 
     NumericCellControl nUpDown = DataGridView.EditingControl as NumericCellControl; 

     // Use the default row value when Value property is null. 
     if (this.Value == null) 
     { 
      nUpDown.Value = (Decimal)this.DefaultNewRowValue; 
     } 
     else 
     { 
      //nUpDown.Value = Decimal.Parse(this.Value.ToString()); 
      Object trueValue = this.Value; 
      nUpDown.Value = Decimal.Parse(trueValue.ToString()); 
     } 
    } 

    public override Type EditType 
    { 
     get 
     { 
      // Return the type of the editing control 
      return typeof(NumericCellControl); 
     } 
    } 

    public override Type ValueType 
    { 
     get 
     { 
      return base.ValueType; 
     } 
     set 
     { 
      base.ValueType = value; 
     } 
    } 

    public override object DefaultNewRowValue 
    { 
     get 
     { 
      // Use 1.0 as the default value. 
      return 1.0m; 
     } 
    } 
} 

NumericCellControl

public class NumericCellControl : NumericUpDown, IDataGridViewEditingControl 
{ 

    private bool Cancelling = false; 

    public NumericCellControl() 
    { 
     this.Increment = 0.1m; 
     this.DecimalPlaces = 1; 
     this.Minimum = 1; 
     this.Maximum = 20; 
    } 

    // Implements the IDataGridViewEditingControl.EditingControlFormattedValue property. 
    public Object EditingControlFormattedValue 
    { 
     get 
     { 
      // must return a String 
      // it doesn't matter if the value is formatted, it will be replaced 
      // by the formatting events 
      return this.Value.ToString(); 
     } 

     set 
     { 
      decimal val = 0; 
      if (value is decimal) 
       val = (decimal)value; 
      else 
      { 
       String s = "" + value; 
       if (s.Length > 0) 
       { 
        decimal.TryParse(s, System.Globalization.NumberStyles.Any, System.Globalization.CultureInfo.CurrentCulture, out val); 
       } 
      } 

      if (val >= this.Minimum && val <= this.Maximum) 
       this.Value = val; 
     } 
    } 

    protected override void OnLeave(EventArgs e) 
    { 
     if (!Cancelling) 
     { 
      var dgv = this.EditingControlDataGridView; 
      var cell = (NumericUpDownCell)dgv.CurrentCell; 
      cell.Value = this.Value; 
     } 

     base.OnLeave(e); 
     Cancelling = false; 
    } 

    protected override void OnKeyDown(KeyEventArgs e) 
    { 
     if (e.KeyCode == Keys.Escape) 
     { 
      Cancelling = true; 
      e.Handled = true; 
      e.SuppressKeyPress = true; 
      var dgv = this.EditingControlDataGridView; 
      dgv.CancelEdit(); 
      dgv.EndEdit(); 
     } 

     base.OnKeyDown(e); 
    } 

    // Implements the IDataGridViewEditingControl.GetEditingControlFormattedValue method. 
    public Object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context) 
    { 
     return EditingControlFormattedValue; 
    } 

    // Implements the IDataGridViewEditingControl.ApplyCellStyleToEditingControl method. 
    public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle) 
    { 
     this.Font = dataGridViewCellStyle.Font; 
     this.ForeColor = dataGridViewCellStyle.ForeColor; 
     this.BackColor = dataGridViewCellStyle.BackColor; 
    } 

    // Implements the IDataGridViewEditingControl.EditingControlRowIndex property. 
    public int EditingControlRowIndex { get; set; } 

    // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey method. 
    public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey) 
    { 
     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: 
      case Keys.Escape:     
       return true; 
      default: 
       return !dataGridViewWantsInputKey; 
     } 
    } 

    // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit method. 
    public void PrepareEditingControlForEdit(bool selectAll) 
    { 
     // No preparation needs to be done. 
    } 

    // Implements the IDataGridViewEditingControl.RepositionEditingControlOnValueChange property. 
    public bool RepositionEditingControlOnValueChange 
    { 
     get 
     { 
      return false; 
     } 
    } 

    // Implements the IDataGridViewEditingControl.EditingControlDataGridView property. 
    public DataGridView EditingControlDataGridView { get; set; } 

    // Implements the IDataGridViewEditingControl.EditingControlValueChanged property. 
    public bool EditingControlValueChanged { get; set; } 

    // Implements the IDataGridViewEditingControl.EditingPanelCursor property. 
    public Cursor EditingPanelCursor 
    { 
     get 
     { 
      return base.Cursor; 
     } 
    } 
} 

NumericColumn

public class NumericColumn : DataGridViewColumn 
{ 
    public NumericColumn() : base(new NumericUpDownCell()) 
    { 
     this.ValueType = typeof(decimal?); 
    } 

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

使用

然後,您可以使用此如下

//Create new Numeric Column 
NumericColumn nCol = new NumericColumn(); 
nCol.ReadOnly = false; 
nCol.Name = "MyColumnName"; 
nCol.HeaderText = "My Numeric Column"; 
nCol.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; 
nCol.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; 

//Assign it to your datagridview 
myDatagridview.Columns.Add(nCol);