【问题标题】:Datagridview Format Column IssueDatagridview 格式列问题
【发布时间】:2015-12-09 17:00:12
【问题描述】:

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

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

我尝试过使用

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

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

有屏蔽列这样的东西吗?

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

提前感谢您的帮助

【问题讨论】:

    标签: c# datagridview datagridviewcolumn


    【解决方案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;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多