gpt4 book ai didi

c# - datagridview 文本框列的逗号分隔符

转载 作者:行者123 更新时间:2023-11-30 22:26:12 27 4
gpt4 key购买 nike

我需要 DataGridView 中的 Currency TextBox,我搜索 Internet 并找到此解决方案 [^]但这在 dataGridView Cell Leave 事件时很有用,我需要在 textchange 中使用逗号分隔符,但是我为此目的写了这个来源:

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
TextBox txt_edit = e.Control as TextBox;
if (txt_edit != null)
{

txt_edit.TextChanged += new EventHandler(txt_edit_TextChanged);
}
}

private void txt_edit_TextChanged(object sender, EventArgs e)
{
TextBox txt = (TextBox) sender;

string str = txt.Text;
str = str.Replace(",", "");
int len = str.Length;
if (len > 3)
{
str = str.Insert(len - 3, ",");
len = len - 3;
while (len > 3)
{
str = str.Insert(len - 3, ",");
len = len - 3;
}
}

dataGridView1.EndEdit();
dataGridView1.CurrentRow.Cells[0].Value = str;
dataGridView1.BeginEdit(false);
}

当我运行我的程序并输入数字时,此源对第一个数字的 3 个正确工作,直到键入第四个数字表示此错误: enter image description here

为什么这个错误编码?有没有更好的方法来解决这个问题?发送

最佳答案

替换这个:

dataGridView1.EndEdit();
dataGridView1.CurrentRow.Cells[0].Value = str;
dataGridView1.BeginEdit(false);

与:

int selStartFromEnd = txt.Text.Length - txt.SelectionStart;
txt.TextChanged -= txt_edit_TextChanged;
txt.Text = str;
txt.TextChanged += txt_edit_TextChanged;
if (txt.Text.Length - selStartFromEnd >= 0)
txt.SelectionStart = txt.Text.Length - selStartFromEnd;
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);

关于c# - datagridview 文本框列的逗号分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12004627/

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