【问题标题】:Datagridview textbox leave eventDatagridview 文本框离开事件
【发布时间】:2017-06-23 22:04:30
【问题描述】:

我有一个将文本框值格式化为货币的函数。我在文本框离开事件中做到了这一点。

private void txtSellingPrice_Leave(object sender, EventArgs e)
{
  txtSellingPrice.Text = FormatCurrency(txtSellingPrice.Text);
}

例如,用户输入 100,输出将是 100 美元。

我的问题是我将如何在 datagridview 单元格中执行此操作?我已经尝试在编辑控件中添加离开事件。我还尝试了 DefaultCellStyle.Format = "C2",这可行,但是当用户更改当前值时,例如 $100.00 更改为 50。输出应为 $50.00。谢谢。

【问题讨论】:

  • 您应该考虑使用 NumericBox 而不是 TextBox,以及在 DataGrid 中使用 NumericColumn 而不是 TextColumn。数字特定控件旨在完全按照您的意愿行事。
  • 谢谢,但我认为 NumericBox 是一个自定义控件。它在我的工具箱中不可用。我正在使用 Visual Studio 2015。可用的是 numericUpDown 控件。
  • 如果我用 BindingSourc 和 BindingListView 创建一个简单的 DataGridView。该列的DevaultCellStype = C2,则值显示为$ 50.00,在键入过程中人们可能会将其更改为12.346,但是一旦离开单元格,它就会自动更改为$ 12.35。这不是你想要的吗?
  • @HaraldCoppoolse 是的,但我没有这样做。如果我在单元格没有变化后输入 100。值仍然是 100。我的 datagridview 没有数据源。我允许用户在 datagridview 中输入值。

标签: c# winforms


【解决方案1】:

简单的方法是将 BindingSource 分配给 DataGridView,将 BindingList 分配给 BindingSoure。将显示货币的列的默认单元格样式格式设置为C2。

如果您这样做了,您的货币列中任何添加/更改/删除的单元格都将自动格式化。

但是,如果您不想使用 BindingSource,则必须自己进行格式化。使用事件 DataGridViewCell.CellValidating 和 DataGridViewCell.CellFormating。

假设您有一个 columnCurrency,其十进制值应以 C2 格式显示。 DefaultCellFormat 设置为 C2。

验证单元格后,检查该值是否真的是小数:

private void OnCellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
    if (e.RowIndex == -1) return;
    if (e.ColumnIndex == this.columnValue.Index)
    {
        decimal value;
        e.Cancel = !Decimal.TryParse((string)e.FormattedValue, out value);
    }
}

每当必须格式化单元格时,格式化 e.Value 中的值:

private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == this.columnValue.Index)
    {
        if (e.Value == null)
        {   // show the Null value:
            e.Value = e.CellStyle.NullValue;
            e.FormattingApplied = true;
        }
        else
        {   // because validated I know value is a decimal:
            decimal value = Decimal.Parse((string)e.Value);
            e.Value = value.ToString(e.CellStyle.Format);
            e.FormattingApplied = true;
        }

        // If desired apply other formatting, like background colouring etc
    }
}

如果您不想使用“C2”作为货币格式,并且更喜欢使用您的函数FormatCurrency,则必须创建一个使用FormatCurrency 格式化的 FormatProvider 并设置 DefaultCellStyle 的 FormatProvider

 private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex == this.columnValue.Index)
    {
        ... (check for null value as described above)
        else
        {
            e.Value = String.Format(e.Value, e.CellStyle.FormatProvider);
            e.FormattingApplied = true;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多