gpt4 book ai didi

c# - Datagridview 格式列问题

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:04 25 4
gpt4 key购买 nike

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

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

我试过用

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

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

有屏蔽列这样的东西吗?

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

提前感谢您的帮助

最佳答案

如果您打算将来更频繁地使用此类行为,请考虑以下链接作为引用 - 特别是最后一个:

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

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;
}
}
}

这应该提供所需的确切结果,同时保留基本值(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;
}
}

关于c# - Datagridview 格式列问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34184621/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com