我需要使用字符串名称访问按钮并更改其BackColor
属性。
我尝试使用this.control[string key]
和this.controls.Find(string, bool)
,但这些都无效。
oleDbConnection.Open();
OleDbCommand command = new OleDbCommand("SELECT * FROM CUSTOMER WHERE FLIGHTNO = '" + variables.depFlightNo + "'", oleDbConnection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string seat = reader[3].ToString();
this.Controls[seat].BackColor = Color.Red;
}
reader.Close();
答案 0 :(得分:1)
oleDbConnection.Open();
OleDbCommand command = new OleDbCommand("SELECT * FROM CUSTOMER WHERE FLIGHTNO = '" + variables.depFlightNo + "'", oleDbConnection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string seat = reader[3].ToString();
foreach (Button s in this.Controls)
//if the controls are in different place
//like panel or groupbox change "this.Controls" to "groupBox.Controls"
{
if (s.Name == seat)
{
s.BackColor = Color.Yellow;
}
}
}
reader.Close();
答案 1 :(得分:0)
如果按钮控件包含在不同的容器而不是表单中,则代码无法找到它们。
而不是this
您需要使用按钮控件容器。 (一个组合框?一个小组?)
因此,例如,如果您的按钮位于名为panel1
的Panel内,则您的循环应更改为
while (reader.Read())
{
string seat = reader[3].ToString();
Controls[] found = this.panel1.Controls.Find(seat, false);
if(found != null && found.Length > 0)
found[0].BackColor = Color.Red;
}
(添加了一些对控件名称的检查,以避免在未找到控件的情况下发生异常)