Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate DataTable with records from database?

This is my GET Method to get my data from my 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 

It returns the DataTable as "pg"

What changes must I make to this GET method to get the records from a table in my database?

C# examples will also do but would be great to see a reply with my code and then the changes....

like image 644
Etienne Avatar asked Jun 16 '26 18:06

Etienne


1 Answers

If Linq to SQL is not an option then you can fall back to ADO.NET. Essentially you will need to create a connection to your database and create and run a command to retrieve the data you require and populate a DataTable. Here is an example if 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);
like image 155
Andy Rose Avatar answered Jun 19 '26 06:06

Andy Rose



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!