views:

1742

answers:

4

In a TextBox, I could use textBox1.SelectionStart = 4. How can I do this in a DataGridView?

edit for clarification: suppose a specific cell is already selected and in editing mode. If I push the right arrow key, the caret moves to the right one position over whatever text is in that cell. I wish to create a button that does the same thing.

+2  A: 

You should probably clarify a bit. Do you mean to change the selected row in a DataGridView or is there a textbox in your DataGridView that you want to move the caret for?

If you're looking to modify the selected row, try the SelectedIndex property.

Scott Anderson
A: 

You need to get the TextBox via the DataGridView's EditingControlShowing event.

Store this is a member variable, and when you need to, access the textBox member and set the SelectionStart as you wrote above.

Something like;

dataGrid.EditingControlShowing += this.dataGrid_EditingControlShowing;

and

void dataGrid_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            if(this.dataGrid.CurrentCell != null && e.Control is TextBox)
            {
                this.currentTextBox = (TextBox)e.Control;
            }
        }
Thies
I tried this out, but when I push (for example) the move-left button, it reselects the entire cell.
Sam Pearson
A: 

Whenever the user would click your button, the cell in the DataGridView would lose focus, so it will remove the edit box, validate the value, and put the formatted value in the cell.

I wonder what your reasons are for having a button move the caret?

mlsteeves
I'm programming a human-machine interface which doesn't have access to a keyboard, but must still have the ability to edit an Xml configuration file.I'm working on a solution now; basically, I'm going to monitor when EditingControlShowing fires (per Thies's suggestion), but simply going to save the current cell to a field, rather than the textbox. When SelectionChanged fires, I'll null currentCell. Then when the butto is pushed, I'll check if there's a currentCell, select it, and use dataGridView.BeginEdit(false).Of course, I'll also have to save the caret position...
Sam Pearson
edit: looks like I don't need to save the current cell, since it doesn't reset when the dataGridView loses focus.
Sam Pearson
A: 

I want to add a symbol on the click of a button after the cursor position in a cell of the gird.

FOr this i need to know the cursor position. I am getting the cursor position with the help of the above code but not everytime mouse is clicked on this cell.

What can i do to get the cursor position on every click done by the user on the cell.

Surbhi