Hide show anchor tag based on Database record and display details in Modal Popup on anchor tag click using jQuery Ajax in ASP.Net

Last Reply on May 05, 2017 08:35 AM By AnandM

Posted on May 05, 2017 04:04 AM

Here is my anchor tag which is in gridview. i need to display only that column which has data.

        <a href="#" id='asc_<%# Eval("Id") %>' class="btn btn-primary btn-sm" onclick="getData(this);" title="data" style="display:none;" >Data
        </a>

        this is my function which is used to show pop up bind the data to pop up.


        function getData(obj) {
            
            var spl = obj.id.split('_');
            var id = spl[1];
           
            if (!isNullOrEmpty(id)) {
                $.ajax({
                    url: "DataFiles.aspx/Description",
                    type: 'POST',
                    contentType: 'application/json;charset=utf-8',
                    datatype: 'json',
                    data: "{id:" + id + "}",
                   
                    success: function (data) {
                        
                      
                        $('#DesPopUp').modal('show');
                        $('#listOfNotes').html('');
                        var divContent = '';
                        divContent += '<div class="pop-grid"> <table class="Grid"> <tbody> <tr>';
                        divContent += '<th> </th><th><u><b style="padding:40px;">Date</b></u></th>';
                        //divContent += '<th><u><b style="padding:40px;">Time</b></u></th>';
                        divContent += '<th><u><b style="padding:40px;">Event</b></u></th>';
                        divContent += '<th><u><b style="padding:45px;">Description</b></u></th>';

                        var i = 0;
                        $.each(data.d, function (key, val) {

                            i++;
                            divContent += '<tr>';
                            //divContent += '<div>1.</div>';
                            divContent += '<td><label><span>' + i + '</span> </td> <td><b>' + val["Date"] + '</b></label> </td>';
                            //divContent += '<td><label> ' + val["Time"] + '</label> </td>';
                            divContent += '<td><label> ' + val["Event"] + '</label> </td>';
                            divContent += '<td><label>' + val["Description"] + '</label> </td>';
                            divContent += '</tr>';
                           
                        });
                        divContent += ' </tbody></table> </div>';
                        $('#listOfNotes').append(divContent);
                       
                       

                    },
                    error: function (data) {
                         //
                    }                    
                });
            }
        }

        function isNullOrEmpty(str) {
            if (str != null && str != '')
                return false;
            else
                return true;
        }

requirement is to show only that column which has data , if no then hide that column in the grid.the id which i am passing to anchor tag is the key, if that id has data in the database it wil bind to div else it wil be empty now how to show grid column which has  data hidde that column which doesnt have.

       [WebMethod]
        public static List<DiaryNotes> Description(string id)
        {            
            using (var conn = new SqlConnection(PageBase.ConString))
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "SP_GetData";
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@Id", id);
                var dt = new DataTable();
                dt.Load(cmd.ExecuteReader());

                List<DiaryNotes> list = new List<DiaryNotes>();
                try
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        DataNote dn = new DataNote();
                        dn.DataNoteDate = row["DataNoteDate"].ToString();
                     //   dn.DataNoteTime = row["DataNoteTime"].ToString();
                        dn.Event = row["Event"].ToString();
                        dn.Description = row["Description"].ToString();
                        list.Add(dn);
                    }
                }
                catch (Exception)
                {
                    throw;
                }
                return list;                
            }
        }

please help ??

You are viewing reply posted by: AnandM on May 05, 2017 08:35 AM.
Posted on May 05, 2017 08:35 AM

Hi Babloo22,

I have created a sample which full fill your requirement you need to modify the code according to your need.

I have used the Northwind Database with tables Customers and Orders.

Refer below article for downloading Northwind Database.

Install the Northwind and Pubs Sample Databases in SQL Server Express

Refer below sample code

HTML

<div>
    <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" OnRowDataBound="RowDataBound">
        <Columns>
            <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" />
            <asp:BoundField DataField="ContactName" HeaderText="ContactName" />
            <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
            <asp:TemplateField>
                <ItemTemplate>
                    <div id="dvShow" runat="server" visible="false">
                        <a href="#" id='asc_<%# Eval("CustomerID") %>' class="btn btn-primary btn-sm" onclick="getData(this);"
                            title="data">Data </a>
                    </div>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
    <div>
        <div class="modal fade" id="DesPopUp" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
            <div class="modal-dialog" role="document">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                            <span aria-hidden="true">&times;</span></button>
                    </div>
                    <div class="modal-body" id="listOfNotes">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
        <script type="text/javascript">
            function getData(obj) {
                var spl = obj.id.split('_');
                var id = spl[1];
                if (!isNullOrEmpty(id)) {
                    $.ajax({
                        url: "Default.aspx/Description",
                        type: 'POST',
                        contentType: 'application/json;charset=utf-8',
                        datatype: 'json',
                        data: "{customerId:'" + id + "'}",
                        success: function (data) {
                            $('#DesPopUp').modal('show');
                            $('#listOfNotes').html('');
                            var divContent = '';
                            divContent += '<div class="pop-grid"> <table class="Grid"> <tbody> <tr>';
                            divContent += '<th> </th><th><u><b style="padding:20px;">CustomerID</b></u></th>';
                            divContent += '<th><u><b style="padding:20px;">OrderID</b></u></th>';
                            divContent += '<th><u><b style="padding:20px;">ShipCountry</b></u></th>';

                            var i = 0;
                            $.each(data.d, function (key, val) {
                                i++;
                                divContent += '<tr>';
                                divContent += '<td><label><span>' + i + '</span> </td> <td><b>' + val["CustomerId"] + '</b></label> </td>';
                                divContent += '<td><label> ' + val["OrderId"] + '</label> </td>';
                                divContent += '<td><label>' + val["ShipCountry"] + '</label> </td>';
                                divContent += '</tr>';
                            });

                            divContent += ' </tbody></table> </div>';
                            $('#listOfNotes').append(divContent);
                        },
                        error: function (data) {
                        }
                    });
                }
            }

            function isNullOrEmpty(str) {
                if (str != null && str != '')
                    return false;
                else
                    return true;
            }
        </script>
    </div>
</div>

C#

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        string query = @"SELECT CustomerID, ContactName, CompanyName FROM Customers
                            WHERE CustomerID IN ('AAFKM','BLAUS','FISSA','WOLAB','QUEDE','PARIS','GALED')";

        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand(query))
            {
                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    cmd.Connection = con;
                    sda.SelectCommand = cmd;
                    using (DataTable dt = new DataTable())
                    {
                        sda.Fill(dt);
                        gvCustomers.DataSource = dt;
                        gvCustomers.DataBind();
                    }
                }
            }
        }
    }
}

protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string customerId = e.Row.Cells[0].Text;
        bool value = CheckDataExists(customerId);
        HtmlControl idTag = (e.Row.FindControl("dvShow") as HtmlControl);
        if (value)
        {
            idTag.Visible = true;
        }
    }
}

public bool CheckDataExists(string customerId)
{
    string query = "SELECT TOP 1 [OrderID],[CustomerID],[ShipCity] ,[ShipCountry] FROM [Orders] WHERE CustomerID = @CustomerID";
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@CustomerID", customerId);
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {

                if (sdr.HasRows)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            con.Close();
        }
    }
}

[WebMethod]
public static List<OrderDetails> Description(string customerId)
{
    string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    string query = "SELECT [OrderID],[CustomerID],[ShipCountry] FROM [Orders] WHERE CustomerID = @CustomerID";
    List<OrderDetails> orderDetails = new List<OrderDetails>();
    using (SqlConnection con = new SqlConnection(constr))
    {
        using (SqlCommand cmd = new SqlCommand(query, con))
        {
            cmd.Parameters.AddWithValue("@CustomerID", customerId);
            con.Open();
            using (SqlDataReader sdr = cmd.ExecuteReader())
            {
                OrderDetails order;
                while (sdr.Read())
                {
                    order = new OrderDetails();
                    order.OrderId = sdr["OrderId"] != null ? Convert.ToInt32(sdr["OrderId"]) : 0;
                    order.CustomerId = sdr["CustomerId"] != null ? sdr["CustomerId"].ToString() : string.Empty;
                    order.ShipCountry = sdr["ShipCountry"] != null ? sdr["ShipCountry"].ToString() : string.Empty;
                    orderDetails.Add(order);
                }

            }
            con.Close();
        }
    }
    return orderDetails;
}

public class OrderDetails
{
    public int OrderId { get; set; }

    public string CustomerId { get; set; }

    public string ShipCountry { get; set; }
}

VB.Net

Private constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Dim query As String = "SELECT CustomerID, ContactName, CompanyName FROM Customers" & vbCr & vbLf & "WHERE CustomerID IN ('AAFKM','BLAUS','FISSA','WOLAB','QUEDE','PARIS','GALED')"

        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand(query)
                Using sda As New SqlDataAdapter()
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using dt As New DataTable()
                        sda.Fill(dt)
                        gvCustomers.DataSource = dt
                        gvCustomers.DataBind()
                    End Using
                End Using
            End Using
        End Using
    End If
End Sub

Protected Sub RowDataBound(sender As Object, e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim customerId As String = e.Row.Cells(0).Text
        Dim value As Boolean = CheckDataExists(customerId)
        Dim idTag As HtmlControl = TryCast(e.Row.FindControl("dvShow"), HtmlControl)
        If value Then
            idTag.Visible = True
        End If
    End If
End Sub

Public Function CheckDataExists(customerId As String) As Boolean
    Dim query As String = "SELECT TOP 1 [OrderID],[CustomerID],[ShipCity] ,[ShipCountry] FROM [Orders] WHERE CustomerID = @CustomerID"
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query, con)
            cmd.Parameters.AddWithValue("@CustomerID", customerId)
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()

                If sdr.HasRows Then
                    Return True
                Else
                    Return False
                End If
            End Using
            con.Close()
        End Using
    End Using
End Function

<WebMethod()> _
Public Shared Function Description(customerId As String) As List(Of OrderDetails)
    Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Dim query As String = "SELECT [OrderID],[CustomerID],[ShipCountry] FROM [Orders] WHERE CustomerID = @CustomerID"
    Dim orderDetails As New List(Of OrderDetails)()
    Using con As New SqlConnection(constr)
        Using cmd As New SqlCommand(query, con)
            cmd.Parameters.AddWithValue("@CustomerID", customerId)
            con.Open()
            Using sdr As SqlDataReader = cmd.ExecuteReader()
                Dim order As OrderDetails
                While sdr.Read()
                    order = New OrderDetails()
                    order.OrderId = If(sdr("OrderId") IsNot Nothing, Convert.ToInt32(sdr("OrderId")), 0)
                    order.CustomerId = If(sdr("CustomerId") IsNot Nothing, sdr("CustomerId").ToString(), String.Empty)
                    order.ShipCountry = If(sdr("ShipCountry") IsNot Nothing, sdr("ShipCountry").ToString(), String.Empty)
                    orderDetails.Add(order)

                End While
            End Using
            con.Close()
        End Using
    End Using
    Return orderDetails
End Function

Public Class OrderDetails
    Public Property OrderId() As Integer
        Get
            Return m_OrderId
        End Get
        Set(value As Integer)
            m_OrderId = value
        End Set
    End Property
    Private m_OrderId As Integer

    Public Property CustomerId() As String
        Get
            Return m_CustomerId
        End Get
        Set(value As String)
            m_CustomerId = value
        End Set
    End Property
    Private m_CustomerId As String

    Public Property ShipCountry() As String
        Get
            Return m_ShipCountry
        End Get
        Set(value As String)
            m_ShipCountry = value
        End Set
    End Property
    Private m_ShipCountry As String
End Class

ScreenShot