技术开发 频道

ASP.NET 控件开发基础

  通过查看System.Web.UI.HtmlControls命名空间,我们可以发现,很多HTML对应的标签都可以通过添加runat=”server”属性转化为服务器控件,比如<table>会转化为HtmlTable对象,但像<input >标签可以通过type属性对应不同的服务器对象。当html内的标签没有和上图中的服务器控件匹配时,所有不匹配的html标签都会通过添加runat=”server”转化为HtmlGenericControl服务器控件。下面是对应的服务器控件类与HTML标签之间的对应关系:

HTML Tag

HTML Server Control

<form>

HtmlForm

<input type="text">

HtmlInputText

<input type="password">

HtmlInputText

<input type="radio">

HtmlInputRadioButton

<input type="checkbox">

HtmlInputCheckBox

<input type="submit">

HtmlInputButton

<input type="hidden">

HtmlInputHidden

<input type="button">

HtmlInputButton

<input type="image">

HtmlInputImage

<input type="file">

HtmlInputFile

<button>

HtmlButton

<select>

HtmlSelect

<textarea>

HtmlTextArea

<img>

HtmlImage

<a>

HtmlAnchor

<table>

HtmlTable

<tr>

HtmlTableRow

<td>

HtmlTableCell

其他标签

HtmlGenericControl

  Demo:动态构建html表格

  通过在前台设置表格的行(x)和列(y),动态的利用System.Web.UI.HtmlControls命名空间下的控件动态的进行设置表格的大小:

  前台代码如下:

<h3>HTML Controls</h3>

X

<input type="text" id="XTextBox" runat="server" /><br />

<br />

Y

<input type="text" id="YTextBox" runat="server" /><br />

<br />

<input type="submit" id="BuildTableButton" runat="server"

value
="Build Table" onserverclick="BuildTableButton_ServerClick" /><br />

<br />

<span id="Span1" runat="server"></span>

</div>

 

  后台代码如下:

protected void BuildTableButton_ServerClick(object sender, EventArgs e)

    {

        
int xDim = Convert.ToInt32(XTextBox.Value);

        
int yDim = Convert.ToInt32(YTextBox.Value);

        BuildTable(xDim, yDim);

    }

    
private void BuildTable(int xDim, int yDim)

    {

        HtmlTable table;

        HtmlTableRow row;

        HtmlTableCell cell;

        HtmlGenericControl content;

        table
= new HtmlTable();

        table.Border
= 1;

        
for (int y = 0; y < yDim; y++)

        {

            row
= new HtmlTableRow();

            
for (int x = 0; x < xDim; x++)

            {

                cell
= new HtmlTableCell();

                cell.Style.Add(
"font", "18pt");

                cell.Style.Add(
"background-color", "blue");

                cell.Style.Add(
"color", "red");

                content
= new HtmlGenericControl("SPAN");

                content.InnerHtml
= "X:" + x.ToString() +

                
"Y:" + y.ToString();

                cell.Controls.Add(content);

                row.Cells.Add(cell);

            }

            table.Rows.Add(row);

        }

        Span1.Controls.Add(table);

    }

 

  这段代码通过构建HtmlTable对象,然后在其内部通过循环的方式加入tr和td.最后将结果放入标签中显示。

  注意下面几行代码:

                cell = new HtmlTableCell();

                cell.Style.Add("font", "18pt");

                cell.Style.Add("background-color", "blue");

                cell.Style.Add("color", "red");

  可以通过html的style属性的add方法添加CSS的键-值对应(有点HashTable的感觉),在render(输出)到客户端的过程中会自动应用其CSS样式(注意,因为全部是string作为键和值的参数,所以要小心你的拼写)

0
相关文章