How prevent Controls binding to Panel

My form has a row of buttons along the top and another along the bottom. In order to improve the appearance, I put a Panel behind each of the two rows. This gives me the problem that I can no longer have a routine which can refer to any button. This is because I now need to include the name of the panel in the reference.

For instance, I have a routine which makes the button forecolor red when it gets the focus.

Internal void ButtonGotFocus()
{
    CurrentFieldName = this.ActiveControl.Name;
    this.Controls[CurrentFieldName].ForeColor = Color.FromArgb(192, 0, 0);
}

This routine now generates a null reference error for buttons which reside within a panel. I just want the panels to make my form look more presentable. I don't want to use them as a container. Can I disable this functionality?


If it's two panels, then you would have to check each panel:

if (Panel1.Controls.ContainsKey(CurrentFieldName)) {
  Panel1.Controls[CurrentFieldName].ForeColor = Color.FromArgb(192, 0, 0);
} else if (Panel2.Controls.ContainsKey(CurrentFieldName)) {
  Panel2.Controls[CurrentFieldName].ForeColor = Color.FromArgb(192, 0, 0);
}

Or you can create a Dictionary and reference the controls that way:

Dictionary<string, RadioButton> rboxes = new Dictionary<string, RadioButton>();
rboxes.Add(radioButton1.Name, radioButton1);
rboxes.Add(radioButton2.Name, radioButton2);
rboxes.Add(radioButton3.Name, radioButton3);
rboxes.Add(radioButton4.Name, radioButton4);

if (rboxes.ContainsKey(CurrentFieldName)) {
  rboxes[CurrentFieldName].ForeColor = Color.FromArgb(192, 0, 0);
}
链接地址: http://www.djcxy.com/p/61570.html

上一篇: 在C#的不同面板中使用相同名称的控件

下一篇: 如何防止控件绑定到面板