用数据库中的记录填充DataTable?

Eti*_*nne 2 c# database vb.net asp.net methods

这是我从我的DataTable获取数据的GET方法

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 
Run Code Online (Sandbox Code Playgroud)

它将DataTable作为"pg"返回

我必须对此GET方法进行哪些更改才能从数据库中的表中获取记录?

C#示例也可以,但很高兴看到我的代码回复然后更改....

And*_*ose 13

如果Linq to 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);
Run Code Online (Sandbox Code Playgroud)