Hi tanweeruddinb...
Check this example. Now please take its reference and correct your code.
Namespaces
C#
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
VB.Net
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Code
C#
protected void Page_Load(object sender, EventArgs e)
{
List<string> columns = new List<string>();
columns.Add("CustomerId");
columns.Add("Name");
columns.Add("Country");
DataTable dt = GetData(columns, "Customers", "CustomerId", "1");
}
private DataTable GetData(List<string> columns, string table, string whereColumn, string whereColumnValue)
{
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
string query = string.Format("SELECT {0} FROM {1} WHERE {2} = {3}", string.Join(",", columns), table, whereColumn, whereColumnValue);
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand(query);
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
Dim columns As List(Of String) = New List(Of String)()
columns.Add("CustomerId")
columns.Add("Name")
columns.Add("Country")
Dim dt As DataTable = GetData(columns, "Customers", "CustomerId", "1")
End Sub
Private Function GetData(ByVal columns As List(Of String), ByVal table As String, ByVal whereColumn As String, ByVal whereColumnValue As String) As DataTable
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Dim query As String = String.Format("SELECT {0} FROM {1} WHERE {2} = {3}", String.Join(",", columns), table, whereColumn, whereColumnValue)
Using con As SqlConnection = New SqlConnection(conString)
Dim cmd As SqlCommand = New SqlCommand(query)
Using sda As SqlDataAdapter = New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As DataTable = New DataTable()
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Function