DataGridView CurrentRow排除新行

时间:2009-08-16 12:06:19

标签: c# datagridview indexing newrow

我想获取DataGridView当前行的索引。问题是,如果当前行是新行,则CurrentRow设置为不是新行的最后一行。我无法检查要选择的行,因为如果选择了一行并不意味着它是当前行并且不一定选择当前行。

我可以获取新行的索引,但是如何知道新行是否是当前行?

3 个答案:

答案 0 :(得分:3)

我通过以下代码挂钩了CellClick事件:

private void uiEntries_CellClick(object sender, DataGridViewCellEventArgs e)
{
    Console.WriteLine(e.RowIndex == uiEntries.NewRowIndex);
}

当该条件为真时,用户'选择'新行。基于该信息,您可能需要实际插入一条新记录(使用..Rows.Add()方法)才能实际执行任何操作,因为新行实际上并不存在于集合中;它只是作为占位符代表一个新行。

答案 1 :(得分:0)

此属性值可以解决您的问题吗?

  

dataGridView1.CurrentCell.RowIndex

答案 2 :(得分:0)

我使用CellEnter事件将CurrentCell.RowIndex保存到表单变量中。单击另一个按钮会导致此事件触发最后一个现有行索引而不是我们需要的新行索引,因此请测试焦点以忽略该情况。

这样可以避免检查所有可能的键和鼠标操作,这些操作可能会像使用CellClick事件一样将光标移动到新行。

从VB自动转换的代码:

private int ActualCurrentRowIndex;

private void DataGridView1_CellEnter(object sender, System.Windows.Forms.DataGridViewCellEventArgs e)
{
    if (DataGridView1.Focused) {
        ActualCurrentRowIndex = DataGridView1.CurrentCell.RowIndex;
    }
}