1. 程式人生 > >DataTable繫結Table控制元件中的資料(vb.net之經典應用)

DataTable繫結Table控制元件中的資料(vb.net之經典應用)

Sub bind_table(ByVal tbl As DataTable)
Dim cn AsNew SqlClient.SqlConnection(P_Con)
        
Dim cmd As SqlClient.SqlCommand = cn.CreateCommand
        
Dim adpt AsNew SqlClient.SqlDataAdapter(cmd)
        
Dim tbl AsNew DataTable                                  // 資料繫結,繫結Table表          
        cmd.CommandTimeout 
=3000
        
Try
         cmd.CommandText 
=str
    adpt.Fill(tbl)
        
Dim i AsInteger
        
Dim j AsInteger
        
Dim trblm As DataRow = tbl.NewRow       先新增一行,並給該行的元素賦初始值
        trblm.Item(
0="合計"
        trblm.Item(
1= tbl.Compute("sum(inum)""")
        trblm.Item(
"heji"= tbl.Compute("sum(heji)
""")//對heji欄位這一列,進行求和運算運算
        trblm.Item(
"zdinum"= tbl.Compute("sum(zdinum)""")
        trblm.Item(
"zdiprice"= tbl.Compute("sum(zdiprice)""")
        trblm.Item(
"zdheji"= tbl.Compute("sum(zdheji)""")
        trblm.Item(
"ewinum"= tbl.Compute("sum(ewinum)""")
        trblm.Item(
"ewiprice
"= tbl.Compute("sum(ewiprice)""")
        trblm.Item(
"ewheji"= tbl.Compute("sum(ewheji)""")
        trblm.Item(
"xpinum"= tbl.Compute("sum(xpinum)""")
        trblm.Item(
"xpiprice"= tbl.Compute("sum(xpiprice)""")
        trblm.Item(
"xpheji"= tbl.Compute("sum(xpheji)""")
        tbl.Rows.InsertAt(trblm, 
0)//將合計插入第一行,插入到DataTable物件中(指定位置的插入操作)
 
        
For i =0To tbl.Rows.Count – 1//統計當前dataTable表中所有行的個數
            
Dim tr AsNew UI.WebControls.TableRow   //(此處定義的是一個TableRow控制元件)
            
For j =0To tbl.Columns.Count – 1//統計當前dataTable表中列的個數
                
Dim thecell AsNew UI.WebControls.TableCell//此處定義了一個單元格
                thecell.Font.Size 
= FontUnit.Point(9)
                thecell.BorderStyle 
= BorderStyle.Solid //給每一個單元格的屬性賦值
                thecell.BorderWidth 
= Unit.Point(1)   //指定了當前表的邊框寬度,控制表的美觀
                
IfIsNumeric(IIf(tbl.Rows(i)(j) Is DBNull.Value, "", tbl.Rows(i)(j))) =TrueThen
                    thecell.HorizontalAlign 
= HorizontalAlign.Right(指定對齊方式為右對齊)
//指定表中內容的對齊方式,用IF語句判斷是數字型別還是文字型別,如為數字型別,則左對齊,反之,右對齊
                
Else
                    thecell.HorizontalAlign 
= HorizontalAlign.Left(指定對齊方式為左對齊)
                
EndIf
                thecell.Wrap 
=False
               thecell.Height 
= Unit.Pixel(20)//指定當前單元格的高度和寬度
                thecell.Width 
= Unit.Pixel(80)
                thecell.RowSpan 
=1
                
If i =0And (j =4or j =7or j =10Then
                    thecell.Text 
=""
                
Else
//本迴圈體中最重要的一句程式碼
                    thecell.Text 
=IIf(tbl.Rows(i)(j) Is DBNull.Value, "", tbl.Rows(i)(j))
                
EndIf
                tr.Cells.Add(thecell)  
//往TableRow控制元件新增單元格操作,
//迴圈一次新增一行。直到DataTable中資料全部讀出為止,這樣就實現了將資料虛擬表(DataTable)中的資料全部繫結在Table控制元件上
            
Next
            Table2.Rows.Add(tr)   
//往Table控制元件中新增行操作
        
Next
    
End Sub