C# 动态创建 控件

2015年01月14日 10:48 0 点赞 0 评论 更新于 2025-11-21 14:20

在编写程序时,为了提高开发效率和灵活性,程序员常常需要动态创建常用的控件。那么,在 C# 中如何动态创建控件呢?本文将详细介绍 C# 动态创建控件的方法。

动态创建的基本概念与示例类型

在 C# 中,动态创建控件意味着在程序运行时生成并添加控件,而不是在设计阶段就固定好界面布局。下面我们将通过创建 FormTableTableRowTableCell 等控件来展示动态创建的过程。

动态创建 Form

可以直接从标准控件中继承来创建 Form,以下是一个简单的示例代码:

Form1 = new HtmlForm();
this.Controls.Add(Form1);

动态创建 Table

创建 HtmlTable 控件的代码如下:

HtmlTable ht1 = new HtmlTable();

动态创建 TableRow 和 TableCell

创建 TableRowTableCell 控件的代码如下:

TableRow tr = new TableRow();
TableCell tc = new TableCell();

在 Form 中添加控件

Table 控件添加到 Form 中的代码如下:

form1.Controls.Add(table);

在 HtmlTable 中添加行和单元格

HtmlTable 中添加 HtmlTableRow,并在 HtmlTableRow 中添加 HtmlTableCell 的代码如下:

htmltable.Rows.Add(htmltablerow);
htmltablerow.Cells.Add(htmltablecell);

在 HtmlTable 中添加其他控件

可以将其他控件添加到 HtmlTable 中,示例代码如下:

htmltable.Controls.Add(OtherControl);

设置控件属性

直接设置文本属性

Label 控件为例,直接设置其文本属性的代码如下:

label.Text = "sadfsf";

设置背景颜色

设置 HtmlTable 背景颜色的代码如下:

htmltable.Attributes["background"] = "a.jpg";

完整示例代码

以下是一个完整的动态创建控件的示例代码,包含了上述各种控件的创建、添加和属性设置:

private void InitializeComponent()
{
Form1 = new HtmlForm();
this.Controls.Add(Form1);

Label lb1 = new Label();
Label lb2 = new Label();
TextBox tb1 = new TextBox();
TextBox tb2 = new TextBox();
Label lb3 = new Label();
Label lb4 = new Label();
DropDownList ddl4 = new DropDownList();
TableRow tr = new TableRow();
DropDownList ddl1 = new DropDownList();

Form1.Controls.Add(lb1);
lb1.Text = "会员卡号";

Form1.Controls.Add(tb1);

lb2.Text = "姓名";

Table table1 = new Table();
Form1.Controls.Add(table1);
table1.Rows.Add(tr);

TableCell tabcl1 = new TableCell();
tr.Cells.Add(tabcl1);
tabcl1.Controls.Add(lb2);

Form1.Controls.Add(tb2);
table1.Rows.Add(tr);
tr.Cells.Add(tabcl1);
tabcl1.Controls.Add(ddl1);

HtmlTable ht = new HtmlTable();
Form1.Controls.Add(ht);
ht.Border = 0;
ht.CellPadding = 0;
ht.CellSpacing = 0;
ht.Height = "100";
ht.Width = "100%";
ht.Attributes["background"] = "a.jpg";

HtmlTableRow htr = new HtmlTableRow();
HtmlTableCell htc = new HtmlTableCell();
ht.Rows.Add(htr);
htr.BorderColor = "red";
htr.Height = "70";
htr.Cells.Add(htc);
htc.BorderColor = "black";
htc.Height = "50";
htc.Controls.Add(lb4);
lb4.Text = "asdfsf";

Form1.Controls.Add(ddl4);
ddl4.Items.Add(new ListItem("男", "M"));
ddl4.Items.Add(new ListItem("女", "F"));
}

通过以上步骤和示例代码,你可以在 C# 中动态创建各种控件,并对其进行属性设置,从而实现灵活的界面布局。

作者信息

feifeila

feifeila

共发布了 3994 篇文章