Datagridview格式列问题

时间:2015-12-09 17:00:13

标签: c# datagridview datagridviewcolumn

我正在尝试以两种不同格式格式化2列

第一列4位数宽度,当用户输入1234时,我需要输出为123.4。

我尝试使用

__dgw.Columns["column"].DefaultCellStyle.Format = "N1";

但输出是1,234.0我不想要逗号,只需要123.4我试过d1等

是否有遮掩栏这样的东西?

我还需要一种方法来创建另一个带有## - ## - ##掩码的列?

提前感谢您的帮助

1 个答案:

答案 0 :(得分:1)

如果您打算在将来更频繁地使用此类行为,请考虑以下链接以供参考 - 尤其是最后一个:

如果这是一次性交易,可能会减少以下工作:

this.dataGridView1.Columns[0].DefaultCellStyle.Format = "000.0";
this.dataGridView1.Columns[1].DefaultCellStyle.Format = "00-00-00";

this.dataGridView1.CellFormatting += this.DataGridView1_CellFormatting;

private void DataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  int value = 0;

  if (e.Value != null && int.TryParse(e.Value.ToString(), out value))
  {
    if (e.ColumnIndex == 0)
    {
      // Must manually move decimal. Setting Format will not do this for you.
      e.Value = (decimal)value / 10;
    }
    else if (e.ColumnIndex == 1)
    {
      // Format won't affect e.Value of type string.
      e.Value = value;
    }
  }
}

这应该提供所需的确切结果,同时保留基础值。

╔════════════╦═══════════╦═══════════════════╗
║ User Input ║ Displayed ║ Actual Cell Value ║
╠════════════╬═══════════╬═══════════════════╣
║    1234    ║   123.4   ║       1234        ║
║   123456   ║  12-34-56 ║      123456       ║
╚════════════╩═══════════╩═══════════════════╝

这也假设您已将用户分别限制为长度为4和6的数字条目,可以按如下方式进行:

this.dataGridView1.EditingControlShowing += this.DataGridView1_EditingControlShowing;

private void DataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
  e.Control.KeyPress -= new KeyPressEventHandler(AllowNumericOnly);
  if (dataGridView1.CurrentCell.ColumnIndex == 0 || dataGridView1.CurrentCell.ColumnIndex == 1)
  {
    TextBox tb = e.Control as TextBox;
    if (tb != null)
    {
      tb.Tag = dataGridView1.CurrentCell.ColumnIndex == 0 ? 4 : 6;
      tb.KeyPress += new KeyPressEventHandler(this.AllowNumericOnly);
    }
  }
}

private void AllowNumericOnly(object sender, KeyPressEventArgs e)
{
  var control = sender as Control;
  int length = (int)control.Tag;

  if (!char.IsControl(e.KeyChar) && (!char.IsDigit(e.KeyChar) || control.Text.Length >= length))
  {
    e.Handled = true;
  }
}