在DataGridView C#中选择行时选择单元格

时间:2013-12-23 05:39:03

标签: c# datagridview

每当在DataGridView中选择一行时,我希望选择一个特定的单元格而不是选择行,并且光标应该在单元格中开始闪烁以进行输入。

4 个答案:

答案 0 :(得分:1)

您需要将SelectionMode的{​​{1}}从DataGridView更改为FullRowSelect

试试这个:

CellSelect

如果您想要编辑所选的dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.CellSelect; 只需双击Cell即可进入EditMode

答案 1 :(得分:1)

您可以使用RowEnterCellBeginEdit事件来实现此目标。

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

当选择一行并且用户开始输入时,始终会编辑第一个单元格,我们可以通过设置CurrentCell属性来设置要编辑的单元格。

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

答案 2 :(得分:0)

首先,您应该参考Selection Modes in the Windows Forms DataGridView Control
这就是如何获得所选单元格的值

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

答案 3 :(得分:0)

你可以得到这样的位置

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