CaMeX CaMeX - 1 year ago 112
C# Question

Load Button name from SQL and change BackColor

On LOAD my WPF is running this code, that should change the BackColor of the buttons that are listed in my Database.

So "reader1.GetString("seat")" have the Seat number, and i have created buttons with the same name as the seat.
So i just want it to load the seat number from sql, and change the backcolor of that button with the name loaded.

example: "reader1.GetString("seat")" comes up with seat: W12, then my Button W12 should change BackColor.

I'm just getting the error cannot convert string to button.. i Have tried many things, but this will not work for me.

MySqlCommand cmd1 = new MySqlCommand("SELECT * FROM guests", _sqlhost);
MySqlDataReader reader1 = cmd1.ExecuteReader();
while (reader1.Read())
if (reader1.GetString("seat") != null)
string btn = reader1.GetString("seat");
this.Button[btn].BackColor = Brushes.Red;

Answer Source

Try using this code instead:

var myButton = (Button)this.FindName(btn);

Check this post for more info: How can I find WPF controls by name or type?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download