c# - 如何确定在 TableLayoutPanel 中单击的单元格?

标签 c# winforms tablelayoutpanel

我有一个 TableLayoutPanel,我想向我单击的单元格添加一个控件。

问题是我无法确定我在运行时单击的单元格。

如何判断被点击的单元格?

最佳答案

您可以使用 GetColumnWidthsGetRowHeights计算单元格行列索引的方法:

Point? GetRowColIndex(TableLayoutPanel tlp, Point point)
{
    if (point.X > tlp.Width || point.Y > tlp.Height)
        return null;

    int w = tlp.Width;
    int h = tlp.Height;
    int[] widths = tlp.GetColumnWidths();

    int i;
    for (i = widths.Length - 1; i >= 0 && point.X < w; i--)
        w -= widths[i];
    int col = i + 1;

    int[] heights = tlp.GetRowHeights();
    for (i = heights.Length - 1; i >= 0 && point.Y < h; i--)
        h -= heights[i];

    int row = i + 1;

    return new Point(col, row);
}

用法:

private void tableLayoutPanel1_Click(object sender, EventArgs e)
{
    var cellPos = GetRowColIndex(
        tableLayoutPanel1,
        tableLayoutPanel1.PointToClient(Cursor.Position));
}

但请注意,仅当单元格尚未包含控件时才会引发点击事件。

关于c# - 如何确定在 TableLayoutPanel 中单击的单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15449504/

相关文章:

c# - 在 Windows 7 64 位中使用 [DllImport ("iphlpapi.dll")]

c# - 从 TableLayoutPanel 中访问组合框的 SelectedIndex

C#套接字接收线程

javascript - javascript 中的 Math.round MidPointRounding.AwayFromZero

c# - 替换 ListView 中列下的项目文本

c# - 动态添加行到表格布局面板

c# - 使用 TableLayoutPanel 的可扩展列(来自代码)

c# - 递归函数调用抛出 StackOverFlowException

c# - 在 CKFinder v3 中将网站成员验证为用户

c# - 使用换行符将 xml 字符串读入文本框