问题
i have a problem when i want to click at last cell in my tableLayoutPanel. When i Run a program, it looks lika this: enter image description here
Next when i click at last cell which i see, everything is ok: enter image description here
But when i scroll tableLayoutPanel an click at the last last cell, it isnt mark last cell, but it mark last cell before scrolling TLP.
Here is my code:
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++;
}
}
回答1:
You need to include the scroll position in your calculations..:
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++;
}
}
来源:https://stackoverflow.com/questions/35814849/i-cant-click-at-last-cell-in-table-layout-panel