簡體   English   中英

如何更改TableLayoutPanel中按鈕的BackColor?

[英]How to change the BackColor of Buttons inside a TableLayoutPanel?

有什么方法可以更改TableLayoutPanel中Button的背景顏色嗎?

單擊TableLayoutPanel外部的Button可以更改Button的背景顏色。
實際上,我想知道如何識別TableLayoutPanel中的Button。
我在下面提供一個代碼塊。 請糾正我。

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是一個集合。 不能將其強制轉換為單個對象。 這個:

tableLayoutPanel1.Controls is Button

將在代碼編輯器(綠色下划線)中通過以下消息通知您:

給定的表達式永遠不會是提供的(“按鈕”)類型。

這個強制轉換將產生一個錯誤:

btnClicked = (Button)tableLayoutPanel1.Controls;

CS0030:無法將類型“ System.Windows.Forms.TableLayoutControlCollection”轉換為“ System.Windows.Forms.Button”


若要修改TableLayoutPanel(或任何其他容器)的所有Button控件子級的屬性,可以枚舉其Controls集合,僅考慮特定類型的子級Controls。

例如,將TableLayoutPanel中所有Button的BackColor屬性更改為Color.Red

foreach (Button button in tableLayoutPanel1.Controls.OfType<Button>()) {
    button.BackColor = Color.Red;
}

更改第一行中所有按鈕的“ Text屬性:
請注意,在這里,我使用的是通用Control類型而不是Button 這是因為Text屬性是所有從Control派生的控件所共有的。 Text屬性在Control類中定義。

foreach (Control ctl in tableLayoutPanel1.Controls.OfType<Button>())
{
    if (tlp1.GetRow(ctl) == 0)
        ctl.Text = "New Text";
}

在TableLayoutPanel的第一行,第一列中修改控件的屬性:
在這里,我不知道哪種控件位於坐標(0, 0) ,但是我知道它是從Control類派生的對象。 因此,我可以設置一個屬於此類且因此被繼承的屬性。
特定屬性與控件類型不相關可能會發生。 在這種情況下,什么都不會發生(您可以嘗試設置TableLayoutPanel的Text屬性)。

(tableLayoutPanel1.GetControlFromPosition(0, 0) as Control).BackColor = Color.Green;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM