2012-08-17 113 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); 
     }