2016-03-05 68 views
0

我想點擊我的tableLayoutPanel中最後一個單元格時出現問題。 當我運行一個程序,它看起來利卡這樣的: enter image description here我無法點擊表格佈局面板中的最後一個單元格

下一頁當我點擊我看到最後一個單元格,一切都很好: enter image description here

但是當我滾動TableLayoutPanel中的點擊在最後的最後單元格,它不標記最後一個單元格,但它在滾動TLP之前標記最後一個單元格。

這裏是我的代碼:

private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e) 
    { 
     row = 0; 
     int verticalOffset = 0; 
     foreach (int h in tableLayoutPanel1.GetRowHeights()) 
     { 
      column = 0; 
      int horizontalOffset = 0; 
      foreach (int w in tableLayoutPanel1.GetColumnWidths()) 
      { 
       Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h); 
       if (rectangle.Contains(e.Location)) 
       { 
        if (column == 1) return; 
        Point cell = new Point(column, row); 

        if (!clickedCells.Contains(cell)) 
        { 

         clickedCells.Add(cell); 
        } 
        else 
        { 

         clickedCells.Remove(cell); 
        } 
        tableLayoutPanel1.Invalidate(); 
        MessageBox.Show(String.Format("row {0}, column {1} was clicked", row, column)); 
        return; 
       } 
       horizontalOffset += w; 
       column++; 
      } 
      verticalOffset += h; 
      row++; 
     } 
    } 
+0

似乎'e.Location'是一個實際的屏幕上,從偏移面板的左上角,而代碼則計算佈局面板座標中的偏移量。因此,e.Location永遠不會大到指向最初看不見的行。也許有一些屬性,如https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.horizo​​ntalscrollingoffset(v=vs.110).aspx面板你使用。在最壞的情況下,您可以將一個單獨的面板放入每個單元格中,並將其「標記」屬性設置爲其位置。 –

+0

然後,您可以使用相同的事件處理程序來處理每個面板的點擊。 –

回答

0

你需要在你的計算滾動位置..:

private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e) 
{ 
    var asp = tableLayoutPanel1.AutoScrollPosition; // <<=== 
    row = 0; 
    int verticalOffset = asp.Y;      // <<=== 
    foreach (int h in tableLayoutPanel1.GetRowHeights()) 
    { 
     column = 0; 
     int horizontalOffset = asp.X;    // <<=== 
     foreach (int w in tableLayoutPanel1.GetColumnWidths()) 
     { 
      Rectangle rectangle = new Rectangle(horizontalOffset, verticalOffset, w, h); 
      if (rectangle.Contains(e.Location)) 
      { 
       if (column == 1) return; 
       Point cell = new Point(column, row); 
       if (!clickedCells.Contains(cell)) 
       { clickedCells.Add(cell);  } 
       else 
       { clickedCells.Remove(cell); } 
       tableLayoutPanel1.Invalidate(); 
       MessageBox.Show(String.Format("row {0}, column {1} was clicked", 
           row, column)); 
       return; 
      } 
      horizontalOffset += w; 
      column++; 
     } 
     verticalOffset += h; 
     row++; 
    } 
} 
+0

非常感謝!它是正確的。 – Miloss

相關問題