2012-08-17 60 views
2

我需要的货币文本框在DataGridView中,我搜索互联网,找到这个解决方案 [^] 但当的dataGridView细胞Leave事件,我需要在textchange逗号分隔符,这是有用的, 但是我写这篇源出于此目的:逗号分隔符为DataGridView的文本框列

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

为什么这个错误线ING? 有没有更好的方法来解决问题? TNX

+0

什么是*错误盘带* ? – V4Vendetta 2012-08-17 11:25:54

回答

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