C# datagridview文本框列的逗号分隔符
我需要货币文本框在DataGridView,我搜索互联网,找到这个解决方案 但这在dataGridView单元格离开事件时很有用,我需要textchange中的逗号分隔符, 然而,我写这篇文章是为了这个目的:C# datagridview文本框列的逗号分隔符,c#,.net,datagridview,controls,C#,.net,Datagridview,Controls,我需要货币文本框在DataGridView,我搜索互联网,找到这个解决方案 但这在dataGridView单元格离开事件时很有用,我需要textchange中的逗号分隔符, 然而,我写这篇文章是为了这个目的: private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) { TextBox txt_e
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个第一位数字,直到键入第四个数字,并记录此错误:
为什么会出现这种错误?
有没有更好的办法来解决这个问题?
tnx这应该有效……(不是100%确定)
替换此项:
dataGridView1.EndEdit();
dataGridView1.CurrentRow.Cells[0].Value = str;
dataGridView1.BeginEdit(false);
与:
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);