代码之家  ›  专栏  ›  技术社区  ›  Etienne

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

  •  2
  • Etienne  · 技术社区  · 14 年前

    这是我从数据表中获取数据的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 
    

    它将数据表返回为“pg”

    要从数据库中的表中获取记录,必须对此get方法进行哪些更改?

    C示例也可以,但如果看到我的代码的回复,然后看到更改,那就太好了……

    1 回复  |  直到 9 年前
        1
  •  13
  •   casperOne    9 年前

    如果linq to sql不是一个选项,那么您可以返回到ado.net。实际上,您需要创建一个到数据库的连接,并创建和运行一个命令来检索所需的数据并填充一个数据表。下面是一个例子,如果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);