table web 控件的用法和传统的html 的table 元素差异很大,为了将网页设计对象导向,table内的列和字段也都跟着对象化了。前面我们已经提过html 控件的htmltable、htmltablerow、htmltablecell 这三个对象,基本上table web 控件里的使用方式和table html 控件没有什么差别。其使用语法为:
<asp:table
id="被程序代码所控制的名称"
runat="server"
backimageurl="url"
cellspacing="像素"
cellpadding="像素"
gridlines="both | horizontal | none | vertical"
horziontalalign="center | justify | left | notset | right"
/>
table web 控件的基本属性如下所示:


我们知道tablecell 对象是tablerow 的子对象,而tablerow 是table 的子物件。只要利用tablerow.cells.add 及table.rows.add 方法就可以建立这些对象的关系。表格的制作方式有两种,一是使用类似html 标注方法,另外一种是用程序动态新增。第一种方法如下范例码所示:
<html>
<asp:table id="table1" backimageurl="vsback.gif" border="1"
runat="server">
<asp:tablerow>
<asp:tablecell>第一列第一行</asp:tablecell>
<asp:tablecell>第一列第二行</asp:tablecell>
<asp:tablecell>第一列第三行</asp:tablecell>
</asp:tablerow>
<asp:tablerow>
<asp:tablecell>第二列第一行</asp:tablecell>
<asp:tablecell>第二列第二行</asp:tablecell>
<asp:tablecell>第二列第三行</asp:tablecell>
</asp:tablerow>
<asp:tablerow>
<asp:tablecell>第三列第一行</asp:tablecell>
<asp:tablecell>第三列第二行</asp:tablecell>
<asp:tablecell>第三列第三行</asp:tablecell>
</asp:tablerow>
</asp:table>
</html>

上面这个程序看起来和html标注里的table 元素几乎一模一样,只不过是标注的名称改为web控件的名称。另外字段内所要显示的的文字,除了使用上面程序的写法外上可写成下列的样式:
<asp:tablecell text="第一列第一行"/>
第二种用程序来动态新增的方法和htmltable 控件一样,我们将html 控件的九九表范例改成用web 控件来写,如下所示:
<html>
<form id="form1" runat="server">
<asp:table id="table1" border="1" runat="server" font-size=14/>
<asp:button id="button1" text="请按我" onclick="button1_click"
runat="server"/>
</form >
<script language="vb" runat="server">
sub button1_click(sender as object, e as eventargs)
dim cell as tablecell
dim row as tablerow
dim x, y as short
for x=1 to 9 step 1
cell=new tablecell
for y=1 to 9 step 1
cell.text+=cstr(x) & " * " & cstr(y) & " = " & cstr(x * y)
if y<>9 then cell.text+="<br>"
next y
if x=1 or x=4 or x=7 then row=new tablerow
row.cells.add(cell)
if x=3 or x=6 or x=7 then table1.rows.add(row)
next x
end sub
</script>
</html>
上面这个程序的用法和htmltable 控件一样,只不过将html 控件改成web 控件罢了。要在表格中显示文字不是问题,若要在表格中放置控件也可以,只要使用tablecell 对象中controls集合的add 方法即可。下列范例码显示如何将对象放到表格中:
<html>
<asp:table id="table1" borderwidth="1px" gridlines="both"
cellspacing="0"
cellpadding="1"
runat="server" />
<script language="vb" runat="server">
sub page_load(sender as object,e as eventargs)
dim i, j as short
for i=0 to 4
dim row as new tablerow
for j=0 to 3
dim cell as new tablecell
cell.text=" column=" & j
if j=3 then
dim btna as new button
btna.text ="column=3"
cell.controls.add(btna)
end if
row.cells.add(cell)
next
table1.rows.add(row)
next
end sub
</script>
</html>

上述程序代码要产生每一列的第四栏时,我们就撰写程序动态的产生一个button 控件,然后将这个button 控件的text 属性设为column=3 后,利用controls 集合的add 方法将button 控件加入cell 对象的controls 集合对象中,最后产生一个第四个字段为button 控件的4 乘5 表格。