Hi dummandumman,
Please refer below Sample.
Database
For this example I have used of Northwind database that you can download using the link given below.
Download Northwind Database
HTML
<table>
<tr>
<td>TableName</td>
</tr>
<tr>
<td><asp:TextBox ID="txtTableName" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td><asp:Button ID="btnSearch" Text="Search" runat="server" OnClick="SearchTable" /></td>
</tr>
</table>
<asp:GridView ID="gvCustomers" runat="server">
</asp:GridView>
Namespaces
C#
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
VB.Net
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
SQL
Stored Procedure
CREATE PROCEDURE [GetDataBasedOnTableName]
@Table_Name VARCHAR(100)
AS
BEGIN
DECLARE @DynamicSQL NVARCHAR(4000)
SET @DynamicSQL = N'SELECT * FROM ' + @Table_Name
EXECUTE sp_executesql @DynamicSQL
END
Code
C#
protected void SearchTable(object sender, EventArgs e)
{
string tableName = txtTableName.Text;
txtTableName.Text = "";
string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand("GetDataBasedOnTableName", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Table_Name", tableName);
con.Open();
this.gvCustomers.DataSource = cmd.ExecuteReader();
this.gvCustomers.DataBind();
con.Close();
}
}
}
VB.Net
Protected Sub SearchTable(ByVal sender As Object, ByVal e As EventArgs)
Dim tableName As String = txtTableName.Text
txtTableName.Text = ""
Dim conString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As SqlConnection = New SqlConnection(conString)
Using cmd As SqlCommand = New SqlCommand("GetDataBasedOnTableName", con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue("@Table_Name", tableName)
con.Open()
Me.gvCustomers.DataSource = cmd.ExecuteReader()
Me.gvCustomers.DataBind()
con.Close()
End Using
End Using
End Sub
Screenshot