1

我有一个带有 , 的应用程序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);
    }
}

但是,只要表单加载和移动鼠标,我就会收到索引超出范围错误。我以前从未使用过这个活动,所以如果有人能指出我哪里出错了,我将不胜感激。

4

1 回答 1

2

The Item[] property which you access in this line of code:

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

is indexed by row and column not by screen coordinates, so your screen coordinates are probably much higher than the number of rows or columns in your grid, therefore causing IndexOutOfRange exception.

You should get the cell using the HitTestInfo class:

    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
    }
于 2012-12-07T18:43:09.010 回答