ASP.NET中根據XML動態創建使用WEB組件
(二)
作者:厲鐵帥
三、動態創建WEB組件。
先來看程序實例:
private void createconfigtable(int totalnum,int[] sequenceint,string[] namestr,string[] ipstr)
{
//根據得到測量點的總數,動態生成輸入框
for(int i=1;i<=totalnum;i++)
{
//創建表格
HtmlTable showtable = new HtmlTable();
showtable.Border=0;
showtable.ID="showtable"+i.ToString();
showtable.BorderColor="#000000";
showtable.CellPadding=4;
showtable.CellSpacing=4;
showtable.Align="center";
myPlaceHolder.Controls.Add(showtable);
//創建一行
HtmlTableRow tRow = new HtmlTableRow();
showtable.Rows.Add(tRow);
//創建第一列(序號)
HtmlTableCell tCell = new HtmlTableCell();
Label sequenceLabel = new Label();
sequenceLabel.ID="sequenceLabel"+i.ToString();
sequenceLabel.Text="序號:";
sequenceLabel.Enabled=true;
tCell.Controls.Add(sequenceLabel);
tRow.Cells.Add(tCell);
//創建第二列
tCell = new HtmlTableCell();
sequencedataTB = new TextBox();
sequencedataTB.ID="sequencedataTB"+i.ToString();
sequencedataTB.Text=i.ToString();
sequencedataTB.Width=30;
sequencedataTB.Text=sequenceint[i].ToString();
sequencedataTB.ReadOnly=false;
//創建第三列(名稱)
tCell = new HtmlTableCell();
Label nameLabel = new Label();
nameLabel.ID="nameLabel"+i.ToString();
nameLabel.Text="名稱:";
nameLabel.Enabled=true;
tCell.Controls.Add(nameLabel);
tRow.Cells.Add(tCell);
//創建第四列
tCell = new HtmlTableCell();
nameTB=new TextBox();
nameTB.ID="nameTB"+i.ToString();
nameTB.Width=120;
nameTB.Text=namestr[i];
nameTB.MaxLength=50;
tCell.Controls.Add(nameTB);
tRow.Cells.Add(tCell);
//創建第五列(IP)
tCell = new HtmlTableCell();
Label ipLabel = new Label();
ipLabel.ID="ipLabel"+i.ToString();
ipLabel.Text="IP:";
ipLabel.Enabled=true;
tCell.Controls.Add(ipLabel);
tRow.Cells.Add(tCell);
//創建第六列
tCell = new HtmlTableCell();
ipTB=new TextBox();
ipTB.ID="ipTB"+i.ToString();
ipTB.Width=120;
ipTB.Text=ipstr[i];
ipTB.MaxLength=15;
tCell.Controls.Add(ipTB);
tRow.Cells.Add(tCell);
}
} tCell.Controls.Add(sequencedataTB);
tRow.Cells.Add(tCell);
… …
//創建第五列(IP)
tCell = new HtmlTableCell();
Label ipLabel = new Label();
ipLabel.ID="ipLabel"+i.ToString();
ipLabel.Text="IP:";
ipLabel.Enabled=true;
tCell.Controls.Add(ipLabel);
tRow.Cells.Add(tCell);
//創建第六列
tCell = new HtmlTableCell();
ipTB=new TextBox();
ipTB.ID="ipTB"+i.ToString();
ipTB.Width=120;
ipTB.Text=ipstr[i];
ipTB.MaxLength=15;
tCell.Controls.Add(ipTB);
tRow.Cells.Add(tCell);
}
}
程序中的myPlaceHolder 是 System.Web.UI.WebControls.PlaceHolder 組件,使用該組件的HTML語法如下:
… …
<tr>
<td>
<asp:PlaceHolder id="myPlaceHolder" runat="server"></asp:PlaceHolder>
</td>
</tr>
… …
使用該組件的目的是為了定位動態創建的表格。該組件在頁面上的位置即為動態創建的表格的位置。
程序中另外一個要說明的地方是動態創建的組件的ID的設定。組件的ID的設定要注意兩點:
1、ID號不能重復
2、要便于在程序中使用。因為要在程序中使用動態創建的組件,要通過該組件的ID來查找。(關于這一點,在“使用動態創建的WEB組件”部分會有較為詳
|