Click here to Skip to main content
15,898,134 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have drop down list,the values of the drop down list are tables(sql tables).while i click table name name from drop down list i need to display the table in grid view or table format.

Note:using ajax/jquery call& web method only in ASP.NET c#.

What I have tried:

I tried but didnt get any solution.Help me guys.
Posted
Updated 18-May-17 19:15pm
Comments
F-ES Sitecore 18-May-17 4:11am    
What you're asking is for someone to write you thousands of lines of code, why would someone do that for free, that's not what this site is for. Break the problem down into smaller managebale chunks and solve each problem one by one.
GrpSMK 18-May-17 5:50am    
atleast share some links
F-ES Sitecore 18-May-17 5:54am    
GrpSMK 18-May-17 6:24am    
i know how to bind single table data through drop down list.But in this scenario table names are in dropdown list,so how to create modal class?
F-ES Sitecore 18-May-17 6:33am    
Pass the name of the table to the controller\webmethod as you would any other bit of data, and from your server code you can use ADO.net to create a DataTable from the table, and you would then interrogate the DataTable to discover the field names\types and that will let you construct your html table.

1 solution

try

ASPX

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">

    <script src="jquery.min.js"></script>
    <title></title>
    <script>
        function funChangeTable(ddlObj) {
            var name = ddlObj.value;

            $.ajax({
                url: 'WebForm1.aspx/GetTableData',
                data: JSON.stringify({ tableName: name }),
                type: 'post',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    var json = JSON.parse(response.d);
                    generateTable(json);
                },
                error: function (a, b, c) {
                    console.log(a, b, c);
                }
            });
        }

        function generateTable(json) {
         
            var $table = $('#tblDynamic');
            $table.find('thead').empty()
            $table.find('tbody').empty()
            if (json && json.length > 0) {
                var header = json[0];
                var columns = [];
                for (var col in header) {
                    columns.push('<th>' + col + '</th>');
                }
                $table.find('thead').append('<tr>' + columns.join('') + '</tr>');
                var rows = [];
                for (var i = 0; i < json.length; i++) {
                    var row = json[i];
                    var tds = [];
                    for (var col in row) {
                        tds.push('<td>' + col + '</td>');
                    }
                    rows.push('<tr>' + tds.join() + '</tr>');
                }
                $table.find('tbody').append(rows.join(''));
            }

        }

    </script>
</head>
<body>

    <form runat="server">
        <asp:DropDownList runat="server" ID="ddlTableNames" onchange="funChangeTable(this)">
        </asp:DropDownList>
        <table id="tblDynamic" border="1">
            <thead></thead>
            <tbody></tbody> 
        </table>


    </form>
</body>
</html>


Code Behind

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
using Newtonsoft.Json; // Add this reference 
using System.Linq;
using System.Collections.Generic;
//http://www.newtonsoft.com/json
//https://www.nuget.org/packages/Newtonsoft.Json/


namespace ExcelGridDemo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        const string connString = "Data Source=.;Initial Catalog=karthik_test;Integrated Security=True";
        protected void Page_Load(object sender, EventArgs e)
        {
            var data = GetAllTableNames(); 
            ddlTableNames.DataSource = data;
            ddlTableNames.DataBind();
            ddlTableNames.Items.Insert(0,"Select a Table");
          
        }

        private static string[] GetAllTableNames() {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("select name from sys.tables", con);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            return dt.AsEnumerable().Select(k => k[0] + "").ToArray();
        }

        [WebMethod]
        public static string GetTableData(string tableName)
        {
            if (GetAllTableNames().Contains(tableName)) // To avoid sql injection
            {
                SqlConnection con = new SqlConnection(connString);
                SqlCommand cmd = new SqlCommand("select * from " + tableName, con);
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                da.Fill(dt);
                string json = JsonConvert.SerializeObject(dt);
                return json;
            }
            else
                return "Table Name Not Found";
        }
         
       
    }
}
 
Share this answer
 
Comments
Karthik_Mahalingam 19-May-17 1:16am    
GrpSMK 19-May-17 3:16am    
Thank you so much.You are genious. But one error,instead of displaying data in tables displaying column names.
Karthik_Mahalingam 19-May-17 3:33am    
means the data is not available for the table.
GrpSMK 19-May-17 5:08am    
No for every table displaying column names only instead of data
Karthik_Mahalingam 19-May-17 5:55am    
check for any error in console window

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900