3

I have a DataGridView, in which I have a column. This column is not readonly, and the purpose of it is to be able to write text in every cell. When I select a empty cell and start typing, it works as expected. However, when there already is text in a cell, and I start typing, all the existing text is removed. How can I prevent this?

Example:

The cell already contains "ABC". When I type D, I want the cell to contain "ABCD", but it only contains "D".

abatishchev
  • 98,240
  • 88
  • 296
  • 433
  • 1
    You have to use (.Text += "test")instead of (.Text = "test") i guess.. Show us some code plz.. – Rob Oct 14 '11 at 09:45
  • @Rob: There is no code to show. This is default behaviour. – Bridget Midget Oct 14 '11 at 09:46
  • Sounds like OP wants to not select the existing text when the textbox to edit the content of the cell shows and have the caret at the end of the textbox – JonAlb Oct 14 '11 at 09:53

1 Answers1

3

Assume dg as your datagridview. Try assigning the following event handler EditingControlShowing, CellEnter, CellLeave to your datagridview. And you should be feeling good now.

    string str = string.Empty;
    int i = 0;

    private void dg_CellEnter(object sender, DataGridViewCellEventArgs e)
    {
        DataGridView dgv = (DataGridView)sender;
        str = dgv[e.ColumnIndex, e.RowIndex].Value.ToString();
    }

    void dg_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
    {
        TextBox tb = (TextBox)e.Control;
        tb.TextChanged += new EventHandler(tb_TextChanged);
    }

    void tb_TextChanged(object sender, EventArgs e)
    {
        if (i == 0)
        {
            i++;
            DataGridViewTextBoxEditingControl dgv = (DataGridViewTextBoxEditingControl)sender;
            string curVal = dgv.Text;
            dgv.Text = str + curVal;
            dgv.SelectionStart = dgv.Text.Length;
        }
        dg.EditingControlShowing -= new DataGridViewEditingControlShowingEventHandler(dg_EditingControlShowing);
        dg.CellEnter -= new DataGridViewCellEventHandler(dg_CellEnter);
    }

    private void dg_CellLeave(object sender, DataGridViewCellEventArgs e)
    {
        i = 0;
    }

Hope it helps.

Sandy
  • 11,332
  • 27
  • 76
  • 122