如何检查用户单击的单元格中是否存在usercontrol。我创建了一个用户控件Rack.cs
,只是想知道如何检查该位置是否存在Rack()
?
如果是,那就做点什么
private void tableLayoutPanel1_MouseClick(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
click++;
var pt = new Point(e.X, e.Y);
var colWidths = this.tableLayoutPanel1.GetColumnWidths();
var rowHeights = this.tableLayoutPanel1.GetRowHeights();
//tableLayoutPanel1.RowStyles.Add(new RowStyle(SizeType.Absolute, 150));
//tableLayoutPanel1.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 150F));
int col = -1, row = -1;
int offset = 0;
for (int iCol = 0; iCol < this.tableLayoutPanel1.ColumnCount; ++iCol)
{
if (pt.X >= offset && pt.X <= (offset + colWidths[iCol]))
{
col = iCol;
break;
}
offset += colWidths[iCol];
}
offset = 0;
for (int iRow = 0; iRow < this.tableLayoutPanel1.RowCount; ++iRow)
{
if (pt.Y >= offset && pt.Y <= (offset + rowHeights[iRow]))
{
row = iRow;
break;
}
offset += rowHeights[iRow];
}
tableLayoutPanel1.Controls.Add(racking[click], col, row);
racking[click].setposition(row, col);
racking[click].SetChannel(click.ToString());
tableLayoutPanel1.ColumnStyles[col].SizeType = SizeType.AutoSize;
Adapter.insertposition(RackID, row, col, click);
}
else if (e.Button == MouseButtons.Right)
{
int[] colWidths = tableLayoutPanel1.GetColumnWidths();
int[] rowHeights = tableLayoutPanel1.GetRowHeights();
int top = tableLayoutPanel1.Parent.PointToScreen(tableLayoutPanel1.Location).Y;
for (int y = 0; y < rowHeights.Length; ++y)
{
int left = tableLayoutPanel1.Parent.PointToScreen(tableLayoutPanel1.Location).X;
for (int x = 0; x < colWidths.Length; ++x)
{
if (new Rectangle(left, top, colWidths[x], rowHeights[y])
.Contains(MousePosition))
{
Control c = tableLayoutPanel1.GetControlFromPosition(x, y);
if (c != null)
{
MessageBox.Show("Yes");
}
}
left += colWidths[x];
}
top += rowHeights[y];
}
}
}
现在我想检查我的Rack控件而不是Rectangle控件,它是否存在?我的Rack控件是文本框和按钮的混合
答案 0 :(得分:1)
在看到一些代码之后,仍然不完全清楚你在做什么(例如,什么是racking
?),但这无论如何都应该有所帮助......
TableLayoutPanel
有一个名为GetControlFromPosition
的方法,可以在给定的单元格(列和行)中获取控件,所以首先你可以这样控制:
var myCellControl = tableLayoutPanel1.GetControlFromPosition(col, row);
您接下来要做的事情取决于您添加控件的方式。如果您直接向每个单元格添加Rack
控件,那么您可以像这样测试它:
if(myCellControl is Rack)
{
//is Rack control, so do someting
}
否则,如果Rack
控件嵌套在容器控件中(例如Panel
),则应循环子控件并测试Rack
控件:
bool hasRack = false;
foreach(Control child in myCellControl.Controls)
{
if(child is Rack)
{
//Rack control found
hasRack = true;
break;
}
}
希望有所帮助