This content originally appeared on DEV Community and was authored by Abu Ben Reaz
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;
}
}
}
This content originally appeared on DEV Community and was authored by Abu Ben Reaz
Abu Ben Reaz | Sciencx (2024-09-15T10:16:01+00:00) Function/Method to get DataTable from SQL Server Database in c#. Retrieved from https://www.scien.cx/2024/09/15/function-method-to-get-datatable-from-sql-server-database-in-c/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.