ASP.NET建立並使用Web組件(2)
來源:互聯網
上載者:User
三、動態建立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組件”部分會有較為詳細的介紹)