2

I need Currency TextBox in DataGridView , I search Internet and Find this solution [^] But this is useful when dataGridView Cell Leave event,I need comma separator in textchange , However I write this source for this purpose :

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

when i run my program and input number this source work correctly for 3 first digit , until type fourth number cording this error: enter image description here

why this error cording? Is there a better way to solve the problem? tnx

0

2 Answers 2

2

Replace this:

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

With:

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);
Sign up to request clarification or add additional context in comments.

Comments

1

This should work....(Not 100% sure)

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.