I've had a look at your problem and whatever is causing your errors, it is
NOT "the problem is that i'm using B1 it's an object from Label class so when i try to change that object backcolor it changes all the labels". That simply doesn't happen because each B1 is a separate instance and setting one of it's properties doesn't affect anything else.
Anyway, I have created a little test project and used most of your code in it. It works fine. I'll show you the code in a moment but I'll explain a couple of changes I've made first.
1. I changed your
TableLayoutPanel
to a
FlowLayoutPanel
because it makes adding the labels easier. To use a TableLayoutPanel you would need to know how many 'cells' you'd need and create that number of columns/rows first. With a FlowLayoutPanel you just keep adding controls and it takes care of the rest.
2. I changed the height of the labels to 25, only because it saved space for my quick test project.
3. The
DataSet
. I knocked up a quick DataSet with one table "Room". That table only has two columns "RoomName" and RoomStatus".
4. I have not used the
DataGrid
part of your code because I am not sure what it does and because it seemed to me to be redundant for this situation. I could be wrong on that and if the code below doesn't help you, you will have to explain what you are using the DGV for in more detail.
So, here's the code that works for me. I hope that you can apply it to your situation.
foreach (DataRow C2 in this.dB1_PureEyezDataSet.Tables["Room"].Rows)
{
try
{
Label B1 = new Label();
B1.BackColor = ((int)C2["RoomStatus"] == 1) ? Color.LimeGreen : ((int)C2["RoomStatus"] == 2) ? Color.Red : Color.Blue;
B1.Width = 104;
B1.Height = 25;
B1.Dock = DockStyle.Fill;
B1.Anchor = AnchorStyles.None;
B1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
FLP1.Controls.Add(B1);
B1.BorderStyle = BorderStyle.FixedSingle;
B1.Text = C2["RoomName"].ToString();
}
catch (Exception)
{
}
}