Is there any way to change the background color of Buttons inside a TableLayoutPanel?
The background color of the Buttons will be changed with a click of a Button outside of the TableLayoutPanel.
Actually I wanted to know how to identify Buttons which are inside a TableLayoutPanel.
I am providing a code block below. Please correct me.
private void button10_Click(object sender, EventArgs e)
{
Button btnClicked = sender as Button;
// wanted to convert the controls of tablelayoutpanel
if (tableLayoutPanel1.Controls is Button)
{
btnClicked = (Button)tableLayoutPanel1.Controls;
}
else
continue;
}
// Couldn't call the buttons inside the tablelayoutpanel.
Control.Controls is a collection. It cannot be cast to a single object. This:
tableLayoutPanel1.Controls is Button
will be notified in the code editor (green underline) with the message:
The given expression is never of the provided ('Button') type.
This cast will instead generate an error:
btnClicked = (Button)tableLayoutPanel1.Controls;
CS0030: Cannot convert type 'System.Windows.Forms.TableLayoutControlCollection' to 'System.Windows.Forms.Button'
To modify a property of all Button controls child of a TableLayoutPanel (or any other container), you can enumerate its Controls collection, considering only the child Controls of a specific Type.
For example, change to Color.Red
the BackColor
property of all Buttons inside a TableLayoutPanel:
foreach (Button button in tableLayoutPanel1.Controls.OfType<Button>()) {
button.BackColor = Color.Red;
}
Change to Text
property of all Buttons in the first Row:
Note that, here, I'm using a generic Control
type instead of Button
. This is because the Text
property is common to all controls that derive from Control . The Text
property is defined in the Control
class.
foreach (Control ctl in tableLayoutPanel1.Controls.OfType<Button>())
{
if (tlp1.GetRow(ctl) == 0)
ctl.Text = "New Text";
}
Modify a property of a Control in the first Row, first Column of the TableLayoutPanel:
Here, I don't know what kind of control is located at coordinates (0, 0)
, but I know it's an object derived from the Control class. So I can set a property that belongs to this class and is threfore inherited.
It may happen that a specific property is not relevant for a control Type. In this case nothing will happen (you can try to set the Text property of your TableLayoutPanel).
(tableLayoutPanel1.GetControlFromPosition(0, 0) as Control).BackColor = Color.Green;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.