【问题标题】:How to access the Index of a changed Selection in a Datagridview如何在 Datagridview 中访问已更改选择的索引
【发布时间】:2015-06-05 08:42:54
【问题描述】:

我正在处理一个 Windows 窗体。目前,我对一个看似简单的问题感到非常头疼。

我有一个 datagridview 并希望允许右键单击选择。因此,我创建了一个名为 dataGridViewJobs_MouseDown 的函数,该函数在 datagridview 上的 MouseDown 上引发:

private void dataGridViewJobs_MouseDown(object sender, MouseEventArgs e)
{
    int curRowIdx = dataGridViewJobs.HitTest(e.Location.X, e.Location.Y).RowIndex;
    if (curRowIdx != -1 && curRowIdx < dataGridViewJobs.Rows.Count)
    {
        dataGridViewJobs.CurrentCell = dataGridViewJobs[0, curRowIdx];
    }
}

执行 hitTest 以查找单击单元格的行索引。然后将datagridview的currentCell设置为该行的第一个单元格。

这会引发 SelectionChanged 事件。这与以下函数有关:

private void dataGridViewJobs_SelectionChanged(object sender, EventArgs e)
{
    if (dataGridViewJobs.Rows.Count > 0)
    {
         Console.WriteLine(dataGridViewJobs.CurrentCell.RowIndex);
    }
 }

这会将旧索引写入控制台。这是为什么?

我目前正在使用一种解决方法,这意味着我将 hitTest 的结果保存在一个全局变量中。但这不是正确的做法。

我做错了吗?提前致谢!

【问题讨论】:

  • 以下是您使用鼠标展开选择时的事件顺序:MouseDown &gt; CellMouseDown &gt; CurrentCellChanged &gt; SelectionChanged &gt; Click &gt; CellClick &gt; MouseClick &gt; CellMouseClick &gt; CellMouseUp &gt; MouseUp

标签: c# winforms datagridview


【解决方案1】:

From MSDN

当您更改 CurrentCell 属性的值时, SelectionChanged 事件发生在 CurrentCellChanged 事件之前。任何 访问 CurrentCell 属性的 SelectionChanged 事件处理程序 这次将获得它之前的值。

使用CurrentCellChanged事件打印当前值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多