Function/Method to get DataTable from SQL Server Database in c#
In this sample, you pass SQL String to the function and get the result in DataTable. You can use this function from anywhere of your application to get DataTable based on SQL String.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DBUtilities
{
public class Program
{
public static void Main(string[] args)
{
//Declare the variable
DataTable MyTable;
//Calling the function to get the result in DataTable
MyTable =GetTable("SELECT * FROM tblAccount”);
}
public static DataTable GetTable(string strSQL)
{
SqlConnection FillConn = new SqlConnection(YourConnetionString);
System.Data.DataTable UserTable = new System.Data.DataTable();
FillConn.Open();
SqlCommand sqlCommand = new SqlCommand();
sqlCommand.Connection = FillConn;
sqlCommand.CommandText = strSQL;
SqlDataAdapter sqlDataAdapter = new SqlDataAdapter();
sqlDataAdapter.SelectCommand = sqlCommand;
sqlDataAdapter.Fill(UserTable);
return UserTable;
}
}
}
Top comments (0)