2013-03-16 231 views

回答

9

您可以使用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)); 
} 

但要注意的是,如果電池沒有click事件只是引發已經包含一個控件。

+0

我無法找到這些方法:( 我使用.netframe工作4.5 – 2013-03-16 15:15:06

+0

@AymanSharaf哪些方法?我的代碼不編譯?你的錯誤信息是什麼? – 2013-03-16 15:31:19

+0

我無法找到GetColumnWidths和GetRowHeights – 2013-03-16 15:45:45

3

這爲我工作:

public TableLayoutPanel tableLayoutPanel { get; set; } 

private void Form_Load(object sender, EventArgs e) 
{ 
    foreach (Panel space in this.tableLayoutPanel.Controls) 
    { 
     space.MouseClick += new MouseEventHandler(clickOnSpace); 
    } 
} 

public void clickOnSpace(object sender, MouseEventArgs e) 
{ 

    MessageBox.Show("Cell chosen: (" + 
        tableLayoutPanel.GetRow((Panel)sender) + ", " + 
        tableLayoutPanel.GetColumn((Panel)sender) + ")"); 
} 

請注意,我的TableLayoutPanel中的全局聲明,這樣我就可以使用它,而無需將它傳遞給每個功能。此外,tableLayoutPanel和其中的每個面板都在其他地方完全以編程方式創建(我的表單[設計]完全是空白的)。

+0

完美。它適合我。 – 2017-02-06 07:03:12

1

我的答案是基於@Mohammad Dehghan的回答以上,但有幾個優點:

  • 現在考慮垂直滾動
  • 的列是按照正確的順序(在i=0,而不是開始i=length),這意味着不同的寬度或高度的列以正確的順序

這裏進行處理是代碼的更新版本:

public Point? GetIndex(TableLayoutPanel tlp, Point point) 
{ 
    // Method adapted from: stackoverflow.com/a/15449969 
    if (point.X > tlp.Width || point.Y > tlp.Height) 
     return null; 

    int w = 0, h = 0; 
    int[] widths = tlp.GetColumnWidths(), heights = tlp.GetRowHeights(); 

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

    for (i = 0; i < heights.Length && point.Y + tlp.VerticalScroll.Value > h; i++) 
    { 
     h += heights[i]; 
    } 
    int row = i - 1; 

    return new Point(col, row); 
} 
相關問題