概述
動態(tài)創(chuàng)建添加控件,可以在一個大容器里一次性放入多個控件。例:根據(jù)文本框中輸入的數(shù)字 給flowLayoutPanel1 添加多少個button。窗體設(shè)計中,需要什么控件就從工具箱里拖出一個控件“掛”在窗體上。其實,窗體上的控件,不但可以“拖”,還可以用代碼動態(tài)生成。動態(tài)生成控件,對需要相同的大量的控件還是比較有用的。
實現(xiàn)方式
1、加載數(shù)據(jù),往panel添加Label 控件。
private void LoadRoomType()
{
DataTable dtRoomType = _roomTypeBLL.GetModelList("", "Code");
pnlRoomType.Controls.Clear();
int padding = 5;
int x = padding, y = padding;
pnlRoom.Controls.Clear();
foreach (DataRow item in dtRoomType.Rows)
{
Label lbl = new Label();
lbl.Text = string.Format("{0}", item["Names"]);
lbl.Image = btnRoomType.Image;
lbl.Cursor = Cursors.IBeam;
lbl.TextAlign = btnRoomType.TextAlign;
lbl.Font = btnRoomType.Font;
lbl.ForeColor = btnRoomType.ForeColor;
lbl.Size = btnRoomType.Size;
lbl.Location = new Point(x, y);
lbl.Tag = item;
lbl.Click += new EventHandler(lbl_Click);
lbl.MouseEnter += new EventHandler(lbl_MouseEnter);
lbl.MouseLeave += new EventHandler(lbl_MouseLeave);
x += lbl.Width + padding;
if (x + lbl.Width > pnlRoomType.Width)
{
x = padding;
y += lbl.Height + padding;
}
pnlRoomType.Controls.Add(lbl);
}
int height = y + (x != padding ? pnlRoomType.Height : 0) + padding;
int addHeight = height - pnlRoomType.Height;
pnlRoom.Top = pnlRoom.Top + addHeight;
pnlRoom.Height = pnlRoom.Height - addHeight;
pnlRoomType.Height = pnlRoomType.Height + addHeight;
if (dtRoomType.Rows.Count > 0)
LoadRoomByTypeID(dtRoomType.Rows[0], 0);
}
2、定義Label 的點擊事件。
void lbl_Click(object sender, EventArgs e)
{
try
{
Label lbl = sender as Label;
DataRow row = lbl.Tag as DataRow;
LoadRoomByTypeID(row, 0);
}
catch (Exception ex)
{
;
}
}
3、定義Label 的鼠標事件。
#region lbl_MouseLeave
void lbl_MouseLeave(object sender, EventArgs e)
{
Label lbl = sender as Label;
lbl.Font = new Font(lbl.Font, FontStyle.Regular);
lbl.Cursor = Cursors.Default;
lbl.ForeColor = btnRoomType.ForeColor;
}
#endregion
#region lbl_MouseEnter
void lbl_MouseEnter(object sender, EventArgs e)
{
Label lbl = sender as Label;
lbl.Font = new Font(lbl.Font, FontStyle.Bold);
lbl.Cursor = Cursors.IBeam;
}
#endregion
效果
該文章在 2024/10/19 12:24:09 編輯過