2010-10-08 49 views
2

这是我的GET方法从获取我的数据我的DataTable用数据库中的记录填充DataTable?

Private Function GetData() As PagedDataSource 
' Declarations  
Dim dt As New DataTable 
Dim dr As DataRow 
Dim pg As New PagedDataSource 

' Add some columns  
dt.Columns.Add("Column1") 
dt.Columns.Add("Column2") 

' Add some test data  
For i As Integer = 0 To 10 
    dr = dt.NewRow 
    dr("Column1") = i 
    dr("Column2") = "Some Text " & (i * 5) 
    dt.Rows.Add(dr) 
Next 

' Add a DataView from the DataTable to the PagedDataSource 
pg.DataSource = dt.DefaultView 

' Return the DataTable  
Return pg 
End Function 

它返回的DataTable为“PG”

我必须对这个GET方法从一个表中的记录在哪些变化我的数据库?

C#示例中也将这样做,但将是巨大的,看看我的代码,然后更改的答复....

+0

对于这种事情我使用Linq-to-Sql或重型项目NHibernate。考虑使用ORM ... – 2010-10-08 08:25:56

+0

我不能使用LINQ,因为它是一个2.0项目.... – Etienne 2010-10-08 08:35:23

回答

12

如果LINQ到SQL是不是一种选择,那么你就可以回落到ADO.NET。本质上,您需要创建与数据库的连接并创建并运行命令以检索所需的数据并填充DataTable。这里是一个例子,如果C#:

// Create a connection to the database   
SqlConnection conn = new SqlConnection("Data Source=MyDBServer;Initial Catalog=MyDB;Integrated Security=True"); 
// Create a command to extract the required data and assign it the connection string 
SqlCommand cmd = new SqlCommand("SELECT Column1, Colum2 FROM MyTable", conn); 
cmd.CommandType = CommandType.Text; 
// Create a DataAdapter to run the command and fill the DataTable 
SqlDataAdapter da = new SqlDataAdapter(); 
da.SelectCommand = cmd; 
DataTable dt = new DataTable(); 
da.Fill(dt);