Saturday, 24 March 2012

Dynamically Bind Tables Data from Database in Frontnd

Store Procedure
alter PROCEDURE DEMO_SCHOOL
(
@table_name varchar(20)
)
AS
BEGIN
DECLARE @cmd AS NVARCHAR(max)
SET @cmd = 'SELECT * FROM ' QUOTENAME(@table_name) 
EXEC sp_executesql  @cmd
END
Page Design

 Source Code

 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ani.aspx.cs" Inherits="Ani" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
      <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click1" />
    
  
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
    
  
    </div>
 
    </form>
</body>
</html>


C# COADING
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

public partial class Ani : System.Web.UI.Page
{
    SqlConnection con;
    SqlCommand cmd;
    SqlDataAdapter da;
    SqlDataReader dr;
    protected void Page_Load(object sender, EventArgs e)
    {
        con = new SqlConnection(ConfigurationManager.ConnectionStrings["satyabrata"].ConnectionString);
    }

    protected void Button1_Click1(object sender, EventArgs e)
    {
        con.Open();
        try
        {
            cmd = new SqlCommand("DEMO_SCHOOL", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@table_name",TextBox1.Text.Trim());
          
           dr= cmd.ExecuteReader();
           GridView1.DataSource = dr;
           GridView1.DataBind();
        
        }
        catch (Exception ex)
        {
            string x = ex.Message.ToString();
        }
        finally
        {
            con.Close();
        }
    }}

No comments:

Post a Comment