TableLayoutPanel Labels Snap To Top Left?
I have a TableLayoutPanel and every time I put a label into one of the cells, it snaps to the top left corner. How can I get to it not do this or change where it snaps.
Also, is 开发者_开发知识库it possible to change a specific cell's background color?
Thanks!
Soo, you can control where a label 'snaps' in a cell by setting the Dock property on the label. It will dock within the confines of the cell. I don't believe you can change the background color of a cell. One way to work around this is to put a panel in each cell, set it to dock using the full cell, and set the back ground color of the panel.
To change the location of a control in a cell use the control's Anchor property.
To change the background color of a cell within a TableLayoutPanel, use the control's CellPaint event to test which Column and/or Row is being painted and set the color accordingly.
The following will set the background color of the cell at 1, 1 to red:
private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e) {
if (e.Column == 1 && e.Row == 1) {
e.Graphics.FillRectangle(Brushes.Red, e.CellBounds);
}
}
@Jay Riggs has the answer. To slightly explain on it:
I've had this trouble. I dont think .Dock would do the trick. In my case, I have been successful by setting
lbl.Anchor = AnchorStyles.None; // to center the label. causes empty left space.
// OR
lbl.Anchor = AnchorStyles.Left // label sticks to left of the container and hence looks neatly aligned along with other controls.
Setting the anchor property is a better solution than dock normally. You can also use the margin property to adjust the position of a label within a cell. It's useful to set the top margin of a lable to 6 or so if you need it to line up with textboxes in the same row.
I can state categorically that you cannot put more than one control in a cell. Do as others have suggested and add your labels to a panel then add the panel to the cell. Flowlayout panels can be good for that, just don't overdo it or things will get very messy.
First set AutoSize
property of label to False
.
Then set TextAlign
property as you desire. It won't span to top left again.
By using Dock and TextAlign Property of label you can set label Text on required place in tablelayoutpanel
精彩评论