获取所选行号随机返回0

时间:2012-11-13 05:04:16

标签: c#

我有一个链接到DGV的上下文菜单条。当单击DGV中的单元格时,它将打开上下文菜单条,我可以单击“plotStripMenuItem”打开一个表单(formPlot),它基本上从文本文件中读取数据并绘制图形并计算将要显示的一些统计信息。返回(一旦formPlot关闭)到之前点击的DGV行。

要执行此操作,我使用“int clickedRow”在打开formPlot之前存储单击的行号,并在关闭formPlot后使用它来更新DGV。

    private void plotToolStripMenuItem_Click(object sender, EventArgs e)
    {
        //get the row number which was clicked 
        string strClickedRow = DGVLeft.CurrentCellAddress.Y.ToString();
        int clickedRow = Convert.ToInt16(strClickedRow);

        FormPlot formPlot = new FormPlot(strLot, pathLD);
        formPlot.ShowDialog();

        DGVLeft.Rows[clickedRow].Cells[0].Value = formPlot.columnA;
        DGVLeft.Rows[clickedRow].Cells[1].Value = formPlot.ColumnB;
        DGVLeft.Rows[clickedRow].Cells[2].Value = formPlot.columnC;
        DGVLeft.Rows[clickedRow].Cells[3].Value = formPlot.columnD;
    }

大部分时间这都按预期工作。但我注意到它偶尔不会更新在打开formPlot之前点击的DGV单元格。相反,它更新了第0行!

e.g。我点击了第7行但是从formPlot返回后,DGV第0行的值是更新的值。不是DGV第7行的值。

对我来说,现在有一种方式是第0行将被更新,因为我点击第7行并将其存储在变量中。

我在这里错过了一些东西吗?

1 个答案:

答案 0 :(得分:1)

这可能会或可能不会解决您的问题,但为什么要将行号转换为字符串然后再转回?

    //get the row number which was clicked 
    string strClickedRow = DGVLeft.CurrentCellAddress.Y.ToString();
    int clickedRow = Convert.ToInt16(strClickedRow);

应该只是

    //get the row number which was clicked 
    int clickedRow = DGVLeft.CurrentCellAddress.Y;