Shaivya Sharma
Shaivya Sharma

Reputation: 137

Selecting a cell at the time of Selecting a row in DataGridView C#

Whenever a row is selected in DataGridView, I want a particular cell to be selected instead of while row being selected and also the cursor should start blinking in the cell for input.

Upvotes: 0

Views: 283

Answers (4)

Kurubaran
Kurubaran

Reputation: 8892

You can use RowEnter and CellBeginEdit events to achieve this.

RowEnter

private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{     
  //Set the selection mode to cell
  dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;

  //When a row is selected always select the cell in index 1
  dataGridView1[1, e.RowIndex].Selected = true;
}

CellBeginEdit

When a row is selected and user start typing always first cell is being edited, We can set the cell to be edited by setting CurrentCell property.

private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
   //set the current cell to be edited to cell in index 1
   dataGridView1.CurrentCell = dataGridView1[1, e.RowIndex];
}

Upvotes: 1

Kumod Singh
Kumod Singh

Reputation: 2163

You can get the location like this

  private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
    {
        int row = 0;
        int verticalOffset = 0;
        foreach (int h in tableLayoutPanel1.GetRowHeights())
        {
            int column = 0;
            int horizontalOffset = 0;
            foreach(int w in tableLayoutPanel1.GetColumnWidths())
            {
                Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h);
                if(rectangle.Contains(e.Location))
                {
                    Trace.WriteLine(String.Format("row {0}, column {1} was clicked", row, column));
                    return;
                }
                horizontalOffset += w;
                column++;
            }
            verticalOffset += h;
            row++;
        }
    }

Upvotes: 0

Sudhakar Tillapudi
Sudhakar Tillapudi

Reputation: 26209

You need to Change SelectionMode of DataGridView from FullRowSelect to CellSelect

Try This:

dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect;

if you want to edit the Cell selected just double click on the Cell to enter into EditMode

Upvotes: 1

zey
zey

Reputation: 6103

First , You should reference Selection Modes in the Windows Forms DataGridView Control !
And this is how to get the selected cell's value

yourGridView.SelectedCells[0].Value.ToString()

Upvotes: 0

Related Questions