DataTable is most commonly used for Data binding. You may need to generate DataTable many times in the whole project. The best practice is to create a method.
In this tutorial, we are going to code a method getDataTable . Lets Start!
Namespaces required for methods
1 2 |
using System.Data; using System.Data.SqlClient; |
Namesapce System.Data is required for DataTable, and System.Data.SqlClient is required for SqlDataAdapter
Get DataTable from SQL Query.
1 2 3 4 5 6 7 8 9 10 |
public DataTable getDataTable(string query) { string connection= "server=Sharp-Coders\SQLEXPRESS;UID=sa;password=sa;database=MyDatabase"; DataTable dataTable1 = new DataTable(); using (SqlDataAdapter dAdapter = new SqlDataAdapter(query, connection)) { dAdapter.Fill(dataTable1); } return dataTable1; } |
You need to pass query in parameter and it returns DataTable
Demo
1 |
DataTable dtSales = getDataTable("Select * from Sales"); |
or
1 2 |
string query = "Select * from Sales"; DataTable dtSales = getDataTable( query ); |