C#winform怎样实现动态生成控件
|
admin
2024年10月18日 12:51
本文热度 150
|
概述
动态创建添加控件,可以在一个大容器里一次性放入多个控件。例:根据文本框中输入的数字 给flowLayoutPanel1 添加多少个button。窗体设计中,需要什么控件就从工具箱里拖出一个控件“挂”在窗体上。其实,窗体上的控件,不但可以“拖”,还可以用代码动态生成。动态生成控件,对需要相同的大量的控件还是比较有用的。
实现方式
1、加载数据,往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 编辑过