為了使HTML界面中的內容能根據數據庫中的內容動態顯示用戶需要的內容,或者根據權限不同要顯示同而實現頁面內容的動態創建
使用HtmlGenericControl創建HTML標簽
引入命名空間: using System.Web.UI.HtmlControls;
更改其屬性: hgg_div.Attributes.Add("style","width:200px; height:200px;");
內容設置: hgg_div.InnerText = "我是一個" + htmlTag;(htmlTag可以是div,br,span…)
或者InnerHtml來給div寫一些html
使用Table newTable = new Table();創建表格控件
newTable.Width = 200;設置高
newTable.Height = 200; 設置寬
創建行: TableRow newTableRow = new TableRow();
newTableRow.Height = 20;
創建單元格: TableCell newTableCell = new TableCell();
newTableCell.Width = 100;
newTableCell.Text = "我是一個單元格";
添加到表格中: newTableRow.Controls.Add(newTableCell);
newTableRow.Controls.Add(newTableCell);
newTable.Controls.Add(newTableRow);
將創建的標簽或者控件添加到頁面中
Page.Controls.Add(newTable);//添加到表單外(control)
Page.Form.InnerHtml=str;//添加到表單內(html)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 8 #region 引入命名空間 9 10 using System.Web.UI.HtmlControls; 11 12 #endregion 13 14 15 namespace Web_CreateHtml 16 { 17 public partial class _Default : System.Web.UI.Page 18 { 19 #region 窗體加載 20 21 protected void Page_Load(object sender, EventArgs e) 22 { 23 CreateHtmlTag("div");//創建一個div 24 CreateTable();//創建一個Table控件 25 JointHtmlTag();//拼接一個div 26 } 27 28 #endregion 29 30 #region 創建HtmlTag 31 32 /// <summary> 33 /// 創建Div,br,span等標簽通用方法 34 /// </summary> 35 private void CreateHtmlTag(string htmlTag) 36 { 37 HtmlGenericControl hgg_div = new HtmlGenericControl(htmlTag); 38 hgg_div.Attributes.Add("style","width:200px; height:200px;"); 39 hgg_div.InnerText = "我是一個" + htmlTag; 40 Page.Controls.Add(hgg_div); 41 } 42 43 #endregion 44 45 #region 創建Table控件 46 47 /// <summary> 48 /// 創建Table控件 49 /// </summary> 50 private void CreateTable() 51 { 52 Table newTable = new Table(); 53 newTable.Width = 200; 54 newTable.Height = 200; 55 TableRow newTableRow = new TableRow(); 56 newTableRow.Height = 20; 57 TableCell newTableCell = new TableCell(); 58 newTableCell.Width = 100; 59 newTableCell.Text = "我是一個單元格"; 60 61 newTableRow.Controls.Add(newTableCell); 62 newTableRow.Controls.Add(newTableCell); 63 newTable.Controls.Add(newTableRow); 64 Page.Controls.Add(newTable); 65 } 66 67 #endregion 68 69 #region 字符串拼接HTML 70 71 /// <summary> 72 /// 字符串拼接HTML 73 /// </summary> 74 private void JointHtmlTag() 75 { 76 string str = "<div style='width:200px;height:200px;'>我是拼接的div</div>"; 77 Page.Form.InnerHtml=str; 78 } 79 80 #endregion 81 } 82 }
最后附上源碼:Asp.net創建實現HTML標簽布局(table,div,br...).zip
作者:曾慶雷
出處:http://www.cnblogs.com/zengqinglei
本頁版權歸作者和博客園所有,歡迎轉載,但未經作者同意必須保留此段聲明, 且在文章頁面明顯位置給出原文鏈接,否則保留追究法律責任的權利