DataGridView上的MouseHover事件 - 索引超出范围

时间:2012-12-07 18:00:38

标签: c# winforms datagridview

我的应用程序带有DataGridView,并且一直在尝试设置MouseHover事件,该事件提供有关正在悬停的单元格的更详细信息。

我的代码如下:

private void dataCaseHistory_MouseHover(object sender, EventArgs e)
{
    try
    {
        DataGridView grid = (DataGridView)sender;
        Point clientPos = grid.PointToClient(Control.MousePosition);
        DataGridViewCell cell = (DataGridViewCell)grid[clientPos.X, clientPos.Y];
        int cellRow = cell.RowIndex;
        int cellColumn = cell.ColumnIndex;

        DataTable table = (DataTable)dataCaseHistory.DataSource;
        int docColumn = table.Columns.IndexOf("Doc");
        if (cellColumn == docColumn)
        {
            var varBundleID = table.Rows[cellRow]["BundleID"];
            if (varBundleID != DBNull.Value && varBundleID != null)
            {
                int bundleID = (int)varBundleID;
                cBundle bundle = new cBundle(bundleID);
                string header = "Bundle: '" + bundle.Name + "'";
                string body = "";
                foreach (DataRow row in bundle.DocumentBundle.Rows)
                {
                    int docID = (int)row["DocumentID"];
                    cDocument doc = new cDocument(docID);
                    body += doc.DocumentName + Environment.NewLine;
                }
                MessageBox.Show(body, header);
            }
            else
            {
                var varDocID = table.Rows[cellRow]["DocID"];
                if (varDocID != DBNull.Value && varDocID != null)
                {
                    int docID = (int)varDocID;
                    cDocument doc = new cDocument(docID);
                    string header = "Document";
                    string body = doc.DocumentName;
                    MessageBox.Show(body, header);
                }
            }
        }                
    }
    catch (Exception eX)
    {
        string eM = "Error occurred when Single Clicking a Document link in the History tab";
        aError err = new aError(eX, eM);
        MessageBox.Show(eX.Message, eM);
    }
}

但是只要表单加载并且每次移动鼠标,我都会得到索引超出范围错误。我之前从未使用过这个活动,所以如果有人能指出我哪里出错了,我会非常感激。

1 个答案:

答案 0 :(得分:2)

您在此行代码中访问的Item []属性:

    DataGridViewCell cell = (DataGridViewCell)grid[clientPos.X, clientPos.Y];

由行和列索引,而不是按屏幕坐标索引,因此您的屏幕坐标可能远高于网格中的行数或列数,因此导致IndexOutOfRange异常。

您应该使用HitTestInfo类获取单元格:

    MouseEventArgs args = (MouseEventaArgs) e;  
    DataGridView.HitTestInfo hitTest = this.grid.HitTest(args.X, args.Y);
    if (hitTest.Type == DataGridViewHitTestType.Cell)
    {
         DataGridViewCell cell = (DataGridViewCell)this.Grid[hitText.ColumnIndex, hitTest.RowIndex];
         // execute business logic here
    }