using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Label[,] label = new Label[256, 256];
public void InitSeats(int seatRow, int seatLine, TabPage tb)
{
for (int i = 0; i < seatRow; i++)
{
for (int j = 0; j < seatLine; j++)
{
label[i, j] = new Label();
label[i, j].BackColor = Color.Yellow;
label[i, j].AutoSize = false;
label[i, j].Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
label[i, j].Location = new System.Drawing.Point(59, 60);
label[i, j].Name = "lbl" + (j + 1).ToString() + "_" + (i + 1).ToString();
label[i, j].Size = new System.Drawing.Size(50, 25);
//设置座位号
label[i, j].Text = (j + 1).ToString() + "-" + (i + 1).ToString();
label[i, j].TextAlign = ContentAlignment.MiddleCenter;
label[i, j].Location = new Point(60 + (i * 90), 60 + (j * 60));
tb.Controls.Add(label[i, j]);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
InitSeats(2, 2, tabPage1);
label[1,2]=new Label();
label[1,2].BackColor=Color.Red;
}
}
}
在代码最后,我想让label[1,2].BackColor=Color.Red的,可以我的做法不对呀,根本就不变色,还是黄色,请高手指点,谢谢!
能说明白一点你要干什么吗?反正你的代码不可能变色的,因为你新创建了一个label 还没放到窗体里,怎么能看到效果呢?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void InitializeLabels()
{
int column = Convert.ToInt32(this.txtRow.Text);
int row = Convert.ToInt32(this.txtColumn.Text);
Label lbl;
for (int i = 0; i < row; i++)
{
for (int j = 0; j < column; j++)
{
lbl = new Label();
lbl.BackColor = Color.Yellow;
lbl.AutoSize = false;
lbl.Font = new System.Drawing.Font("宋体", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134)));
lbl.Location = new System.Drawing.Point(59, 60);
lbl.Name = "lbl" + (j + 1).ToString() + "_" + (i + 1).ToString();
lbl.Size = new System.Drawing.Size(50, 25);
//设置座位号
lbl.Text = (j + 1).ToString() + "-" + (i + 1).ToString();
lbl.TextAlign = ContentAlignment.MiddleCenter;
lbl.Location = new Point(60 + (i * 90), 60 + (j * 60));
this.tabPage1.Controls.Add(lbl);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
//InitSeats(2, 2, tabPage1);
//label[1, 2] = new Label();
//label[1, 2].BackColor = Color.Red;
//Label lbl = (Label)label[1, 2];
//lbl.BackColor = Color.Red;
//通过name来找到你想设置颜色的label lbl1_1
foreach (Control control in this.tabPage1.Controls)
{
int row = Convert.ToInt32(this.txtRow.Text);
int column = Convert.ToInt32(this.txtColumn.Text);
string lblToFind = "lbl"+row.ToString() + "_" + column.ToString();
if (control is Label)
{
if (control.Name.Equals(lblToFind))
{
control.BackColor = Color.Red;
}
}
}
}
private void btnInitializeGrid_Click(object sender, EventArgs e)
{
InitializeLabels();
}
}
}
label[1,2]=new Label();
这句话去掉看看。
实在不行就遍历Controls内所有的label 把你想要的那个更改颜色