2

我需要 DataGridView 中的 Currency TextBox ,我搜索 Internet 并找到这个解决方案[^] 但这在 dataGridView 单元离开事件时很有用,我需要在 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 个第一位数字,直到键入第四个数字来显示此错误: 在此处输入图像描述

为什么会出现这个错误?有没有更好的方法来解决问题?tnx

4

2 回答 2

2

替换这个:

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);
于 2012-08-17T13:57:07.543 回答
1

这应该有效....(不是 100% 确定)

delegate void SetColumnIndex(); 
private void txt_edit_TextChanged(object sender, EventArgs e) 
        { 

 //.....
  dataGridView1.EndEdit(); 

  SetColumnIndex method = new SetColumnIndex(Mymethod); 
  dataGridView1.CurrentRow.Cells[0].Value = str;
  dataGridView1..BeginInvoke(method);

         }         

 private void Mymethod()
        {
            dataGridView1.CurrentCell = myGridView.CurrentRow.Cells[0];
            dataGridView1.BeginEdit(false);
        }
于 2012-08-17T11:26:15.953 回答