DEV Community

Abu Ben Reaz
Abu Ben Reaz

Posted on

2

Function/Method to get DataTable from SQL Server Database in c#


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;
  }
 }
}

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay