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

时间:2010-10-08 08:20:32

标签: c# asp.net database vb.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 

它将DataTable返回为“pg”

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

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

1 个答案:

答案 0 :(得分: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);