Populate ASP.Net GridView on another GridView Selected Row using jQuery AJAX and WebMethod

Last Reply 2 months ago By pandeyism

Posted 2 months ago

Currently, I have two gridviews in my page. One gridview is the header and the other gridview is the details. When I select the header record in the top gridview, I can see the detail lines below in the bottom gridview.

I would like to change the following:

1. The page refreshes when I click the header row to see the details - I would like this to not have to refresh (databind)

2. If I want to add or remove rows in the details the page refreshes on each action - I would like to be able to do this without refreshing (databind)

Is it better to use jquery to complete such tasks or vb.net addrow?

I reviewed this example; however, i would like to be able to add and remove rows without hitting the submit button: https://www.aspsnippets.com/Articles/Dynamically-Add-Rows-to-GridView-using-jQuery-on-Button-Click-in-ASPNet.aspx

VB.net (When I click the header row to show the details, the following code runs)

    Protected Sub gvtfaTrust_SelectedIndexChanged(sender As Object, e As EventArgs) Handles gvtfaTrust.SelectedIndexChanged

        Dim conString As String = ConfigurationManager.ConnectionStrings("mogp_app").ConnectionString
        Using con As New SqlConnection(conString)
            Using cmd As New SqlCommand("usp_Loan")
                cmd.Parameters.AddWithValue("@Action", TryCast(gvtfaTrust.SelectedRow.FindControl("btnSelect"), LinkButton).Text)
                cmd.Parameters.AddWithValue("@User", LabelFullname.Text)
                cmd.Parameters.AddWithValue("@Parameter1", gvtfaTrust.SelectedValue.ToString())
                cmd.Parameters.AddWithValue("@Parameter2", "")
                cmd.Parameters.AddWithValue("@Parameter3", "")
                cmd.Parameters.AddWithValue("@Parameter4", "")
                Using sda As New SqlDataAdapter()
                    cmd.CommandType = CommandType.StoredProcedure
                    cmd.Connection = con
                    sda.SelectCommand = cmd
                    Using dt As New DataTable()
                        sda.Fill(dt)
                        gvtfaLoan.DataSource = dt

                        Dim dv As DataView = dt.AsDataView
                        dv.Sort = "ID ASC"
                        gvtfaLoan.DataSource = dv

                        gvtfaLoan.DataBind()
                        gvtfaLoan.Focus()
                        'Calculate Sum and display in Footer Row
                        Dim total As Decimal = dt.AsEnumerable().Sum(Function(row) row.Field(Of Decimal)("Amount"))
                        gvtfaLoan.FooterRow.Cells(6).Text = "Total"
                        gvtfaLoan.FooterRow.Cells(6).HorizontalAlign = HorizontalAlign.Right
                        gvtfaLoan.FooterRow.Cells(6).Font.Bold = True
                        'gvtfaLoan.FooterRow.Cells(7).Text = total.ToString("C2")
                        gvtfaLoan.FooterRow.Cells(7).HorizontalAlign = HorizontalAlign.Right
                        gvtfaLoan.FooterRow.Cells(7).Font.Bold = True
                    End Using
                End Using
            End Using
        End Using

        btnCloseLoan.Visible = True

        Dim Action As String = TryCast(gvtfaTrust.SelectedRow.FindControl("btnSelect"), LinkButton).Text
        Dim Marked As String = TryCast(gvtfaTrust.SelectedRow.FindControl("btnMark"), CheckBox).Checked

        If (Action = "Allocations" Or Action = "Add") And Marked = False Then
            btnAddLoan.Visible = True
            btnAddLoan.Enabled = True
            gvtfaLoan.Columns(8).Visible = True
        Else
            btnAddLoan.Visible = False
            btnAddLoan.Enabled = False
            gvtfaLoan.Columns(8).Visible = False
        End If

    End Sub

My detail gridview: 

        <asp:GridView ID="gvtfaLoan" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ShowFooter="True" AllowSorting="False" OnRowDataBound="gvtfaLoan_RowDataBound" CssClass="table table-striped table-bordered table-hover" Width="98%" HorizontalAlign="Center">
            <Columns>
                <asp:BoundField DataField="ID" HeaderText="0. ID" ShowHeader="false" HeaderStyle-Wrap="false" SortExpression="ID"/>
                <asp:BoundField DataField="CheckDate" HeaderText="1. Check Date" ShowHeader="false" HeaderStyle-Wrap="false" DataFormatString="{0:dd, MMM yyyy}" SortExpression="CheckDate"/>
                <asp:BoundField DataField="BorrowerName" HeaderText="2. Borrower Name" ShowHeader="false" HeaderStyle-Wrap="false" SortExpression="BorrowerName" />
                <asp:BoundField DataField="CheckNo" HeaderText="3. CheckNo" ShowHeader="false" HeaderStyle-Wrap="false" SortExpression="CheckNo" />                
                <asp:TemplateField HeaderText="4. Check Memo" SortExpression="CheckMemo">
                    <ItemTemplate>
                        <asp:Label ID="LabelCheckMemo" runat="server" Text='<%# Eval("CheckMemo") %>' visible="false"></asp:Label>
                        <asp:TextBox ID="TextCheckMemo" runat="server" Text='<%# Eval("CheckMemo") %>' Visible="false" CssClass="selectpicker show-tick form-control UpdateLoan"  MaxLength="30"></asp:TextBox>
                    </ItemTemplate>
                    <HeaderStyle Wrap="False" />
                </asp:TemplateField>                
                <asp:BoundField DataField="LoanCode" HeaderText="5. Loan Code" ShowHeader="false" HeaderStyle-Wrap="false" SortExpression="LoanCode" />
                <asp:TemplateField HeaderText="6. GL Account" HeaderStyle-HorizontalAlign="Left" SortExpression="GLAcct">
                    <ItemTemplate>
                        <asp:Label ID="LabelGLAcct" runat="server" Text='<%# Eval("GLAcct") %>' Visible="false"></asp:Label>
                        <asp:DropDownList ID="DropdownlistGLAcct" runat="server" Visible="false" CssClass="selectpicker form-control UpdateLoan" data-style="btn btn-default btn-sm" data-live-search-style="true" data-live-search="true"/>
                    </ItemTemplate>
                    <HeaderStyle HorizontalAlign="Left" Wrap="false" />
                </asp:TemplateField>
               
                <asp:TemplateField HeaderText="7. Amount" HeaderStyle-HorizontalAlign="Right" SortExpression="Amount">
                    <ItemTemplate>
                        <asp:Label ID="LabelAmount" runat="server" Text='<%# String.Format("$ {0:N2}", Eval("Amount")) %>' visible="false"></asp:Label>
                        <asp:TextBox ID="TextAmount" runat="server" Text='<%# String.Format(" {0:N2}", Eval("Amount")) %>' Visible="false" style="text-align: right" readonly="true" CssClass="currencyMask form-control UpdateLoan"></asp:TextBox>
                    </ItemTemplate>
                    <FooterTemplate>
                        <asp:Label ID="txtTotal" runat="server" Text='<%# String.Format(" {0:C}", Eval("Amount")) %>'></asp:Label>
                    </FooterTemplate>
                </asp:TemplateField>
                <asp:TemplateField Visible="false">
                    <ItemTemplate>
                        <asp:LinkButton ID="btnDelete" runat="server" Text="Delete" OnClick="DeleteLoan"/>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
         </asp:GridView>

 

You are viewing reply posted by: pandeyism 2 months ago.
Posted 2 months ago

Hey Warren,

Please refer below sample.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=gvtfaTransaction]").find("[id*=btnSelect]").click(function () {
            var row = $(this).closest("tr");
            var index = row[0].rowIndex - 1;
            var custid = row.find("td").eq(0).html();
            $.ajax({
                type: "POST",
                url: "CS.aspx/GetData",
                data: "{custid:" + custid + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("get session failed " + errorThrown);
                },
                success: function (response) {
                    $('#gvtfaDetails').focus();
                    document.activeElement.scrollIntoView(true);
                    var xmlDoc = $.parseXML(response.d);
                    var xml = $(xmlDoc);
                    var customers = xml.find("Table");
                    var row = $("[id*=gvtfaDetails] tr:last-child").clone(true);
                    $("[id*=gvtfaDetails] tr").not($("[id*=gvtfaDetails] tr:first-child")).remove();
                    $.each(customers, function () {
                        $("td", row).eq(0).html($(this).find("CustomerId").text());
                        $("[id*=LabelCheckMemo]", row).html($(this).find("Name").text());
                        $("[id*=TextCheckMemo]", row).val($(this).find("Country").text());
                        $("[id*=gvtfaDetails]").append(row);
                        row = $("[id*=gvtfaDetails] tr:last-child").clone(true);
                    });
                }
            });
            return false;
        });
        $('.Mark').on('change', function () {
            var id = $(this).closest('tr').find('td').eq(0).html();
            var checkbox = $(this).closest('tr').find('[id*=btnMark]');
            var Marked = $(this).closest('tr').find('[id*=btnMark]:checked').val();
            var DropdownlistGLAcct = $(this).closest('tr').find('[id*=DropdownlistGLAcct]');
            var LabelGLAcct = $(this).closest('tr').find('[id*=LabelGLAcct]');
            var TextExchangeRate = $(this).closest('tr').find('[id*=TextExchangeRate]');
            var LabelFullname = document.getElementById('<%=LabelFullname.ClientID%>').innerText;
            $.ajax({
                type: "POST",
                url: "CS.aspx/Mark",
                data: "{id:" + id + ",Marked:'" + Marked + "', LabelFullname:'" + LabelFullname + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                error: function (jqXHR, textStatus, errorThrown) {
                    alert("get session failed " + errorThrown);
                },
                success: function (response) {
                    if (response.d == "failed") {
                        $(checkbox).prop('checked', false);
                        $(DropdownlistGLAcct).prop("disabled", false);
                        $(DropdownlistGLAcct).closest('td').find('button').removeClass('disabled');
                    }
                    else {
                        if ($(checkbox).prop('checked') == false) {
                            $(TextExchangeRate).prop("disabled", false);
                            $(DropdownlistGLAcct).prop("disabled", false);
                            $(DropdownlistGLAcct).closest('td').find('button').removeClass('disabled');
                        }
                        else {
                            $(TextExchangeRate).prop("disabled", true);
                            $(DropdownlistGLAcct).prop("disabled", true);
                            $(DropdownlistGLAcct).closest('td').find('button').addClass("disabled");
                        }
                    }
                }
            });
        });
    });
</script>
<div>
    <asp:Label ID="LabelFullname" Text="Test" runat="server" />
    <asp:GridView ID="gvtfaTransaction" runat="server" AutoGenerateColumns="False" OnRowDataBound="gvtfaTrust_RowDataBound"
        DataKeyNames="ID">
        <Columns>
            <asp:BoundField DataField="ID" HeaderText="0. ID" ShowHeader="false" HeaderStyle-Wrap="false"
                SortExpression="ID" />
            <asp:BoundField DataField="BankAccount" HeaderText="1. Bank Account" HeaderStyle-Wrap="false"
                SortExpression="BankAccount" Visible="false" />
            <asp:BoundField DataField="DateDeposited" HeaderText="2. Date Deposited" DataFormatString="{0:dd, MMM yyyy}"
                HeaderStyle-Wrap="false" SortExpression="DateDeposited" />
            <asp:BoundField DataField="PayName" HeaderText="3. Payee" HeaderStyle-Wrap="false"
                SortExpression="PayName" />
            <asp:BoundField DataField="Reference" HeaderText="4. Reference" HeaderStyle-Wrap="false"
                SortExpression="Reference" />
            <asp:BoundField DataField="Memo" HeaderText="5. Memo" HeaderStyle-Wrap="false" SortExpression="Memo" />
            <asp:BoundField DataField="EntryType" HeaderText="6. Entry Type" HeaderStyle-Wrap="false"
                SortExpression="EntryType" />
            <asp:TemplateField HeaderText="7. GL Account" HeaderStyle-HorizontalAlign="Left"
                SortExpression="GLAcct">
                <ItemTemplate>
                    <asp:Label ID="LabelGLAcct" runat="server" Text='<%# Eval("GLAcct") %>' Visible="false"></asp:Label>
                    <asp:DropDownList ID="DropdownlistGLAcct" runat="server" Visible="false" CssClass="selectpicker show-tick form-control Update"
                        data-style="btn btn-default btn-sm" data-live-search-style="true" data-live-search="true">
                        <asp:ListItem Text="text 1" />
                        <asp:ListItem Text="text 2" />
                    </asp:DropDownList>
                </ItemTemplate>
                <HeaderStyle HorizontalAlign="Left" Wrap="false" />
            </asp:TemplateField>
            <asp:BoundField DataField="Amount" HeaderText="8. Amount" DataFormatString="{0:C}"
                HeaderStyle-Wrap="false" SortExpression="Amount" />
            <asp:TemplateField HeaderText="9. Exchange" SortExpression="ExchangeRate">
                <ItemTemplate>
                    <asp:Label ID="LabelExchangeRate" runat="server" Text='<%# String.Format("{0:0.00000}", Eval("ExchangeRate")) %>'
                        Visible="false"></asp:Label>
                    <asp:TextBox runat="server" ID="TextExchangeRate" Text='<%# Eval("ExchangeRate", "{0:0.00000}") %>'
                        CssClass="btn-sm form-control Update" Width="65px" Enabled='<%# Eval("IsExchangeRate") %>'
                        data-mask="#.##000" />
                </ItemTemplate>
                <HeaderStyle Wrap="False" />
            </asp:TemplateField>
            <asp:TemplateField HeaderText="10. Details" HeaderStyle-Wrap="false" SortExpression="details">
                <ItemTemplate>
                    <asp:LinkButton ID="btnSelect" runat="server" Text='<%# Eval("Details") %>' CommandName="Select"
                        CssClass="Select" CommandArgument="<%# Container.DataItemIndex %>" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="11. Mark" HeaderStyle-Wrap="false" SortExpression="Marked">
                <ItemTemplate>
                    <asp:CheckBox ID="btnMark" runat="server" Checked='<%# Eval("Marked") %>' CssClass="form-check-input Mark" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="12. Ignore" HeaderStyle-Wrap="false" SortExpression="Ignore">
                <ItemTemplate>
                    <asp:CheckBox ID="btnIgnore" runat="server" AutoPostBack="true" Checked='<%# Eval("Ignore") %>'
                        OnCheckedChanged="Ignore_Click" />
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
        <SelectedRowStyle BackColor="lightyellow" />
        <PagerSettings Mode="NumericFirstLast" />
        <PagerStyle CssClass="pagination-ys" HorizontalAlign="Left" />
    </asp:GridView>
    <asp:GridView ID="gvtfaDetails" runat="server" AutoGenerateColumns="False">
        <Columns>
            <asp:BoundField DataField="CustomerId" HeaderText="CustomerId" />
            <asp:TemplateField HeaderText="4. Check Memo">
                <ItemTemplate>
                    <asp:Label ID="LabelCheckMemo" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
                    <asp:TextBox ID="TextCheckMemo" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</div>

Namespaces

C#

using System.Data;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.Data
Imports System.Web.Services
Imports System.Data.SqlClient

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        this.BindGrid();
        this.BindDummyRow();
    }
}

private void BindGrid()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
        new DataColumn("ID", typeof(int)), 
        new DataColumn("BankAccount", typeof(string)), 
        new DataColumn("DateDeposited", typeof(string)), 
        new DataColumn("PayName", typeof(string)), 
        new DataColumn("Reference", typeof(string)), 
        new DataColumn("Memo", typeof(string)), 
        new DataColumn("EntryType", typeof(int)), 
        new DataColumn("GLAcct", typeof(string)), 
        new DataColumn("Amount", typeof(int)), 
        new DataColumn("ExchangeRate", typeof(int)), 
        new DataColumn("IsExchangeRate", typeof(bool)), 
        new DataColumn("Details", typeof(string)), 
        new DataColumn("Marked", typeof(bool)), 
        new DataColumn("Ignore", typeof(bool)) });
    dt.Rows.Add(1, "111", "01/02/2018", "BN", "123455AAA", "CM", 124, "GA", 100, 5, true, "Details", true, true);
    dt.Rows.Add(2, "222", "02/02/2018", "BN1", "123455AAA112", "CM1", 12411, "GA1", 200, 6, true, "Details", true, false);
    gvtfaTransaction.DataSource = dt;
    gvtfaTransaction.DataBind();
}

private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("CustomerId");
    dummy.Columns.Add("Name");
    dummy.Columns.Add("Country");
    dummy.Rows.Add();
    gvtfaDetails.DataSource = dummy;
    gvtfaDetails.DataBind();
}

protected void Ignore_Click(object sender, EventArgs e)
{
}
[WebMethod]
public static string GetData(int custid)
{
    string strconstr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strconstr))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers WHERE CustomerId=@CustomerId", con))
        {
            cmd.Parameters.AddWithValue("@CustomerId", custid);
            using (SqlDataAdapter da = new SqlDataAdapter(cmd))
            {
                using (DataSet ds = new DataSet())
                {
                    da.Fill(ds);

                    return ds.GetXml();
                }
            }
        }
    }
}

[WebMethod()]
public static string Mark(int id, string Marked, string LabelFullname)
{
    try
    {
        int age = int.Parse("1");
        return "success";
    }
    catch (Exception ex)
    {
        return "failed";
    }
}

protected void gvtfaTrust_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.Cells[11].Controls.OfType<CheckBox>().FirstOrDefault().Checked)
        {
            e.Row.Cells[7].Controls.OfType<DropDownList>().FirstOrDefault().Enabled = false;
            e.Row.Cells[7].Controls.OfType<DropDownList>().FirstOrDefault().Visible = true;
            e.Row.Cells[7].Controls.OfType<Label>().FirstOrDefault().Visible = true;
            e.Row.Cells[9].Controls.OfType<TextBox>().FirstOrDefault().Enabled = false;
            e.Row.Cells[12].Controls.OfType<CheckBox>().FirstOrDefault().Enabled = false;
        }
    }
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Me.BindGrid()
        Me.BindDummyRow()
    End If
End Sub

Private Sub BindGrid()
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("ID", GetType(Integer)), New DataColumn("BankAccount", GetType(String)), New DataColumn("DateDeposited", GetType(String)), New DataColumn("PayName", GetType(String)), New DataColumn("Reference", GetType(String)), New DataColumn("Memo", GetType(String)), New DataColumn("EntryType", GetType(Integer)), New DataColumn("GLAcct", GetType(String)), New DataColumn("Amount", GetType(Integer)), New DataColumn("ExchangeRate", GetType(Integer)), New DataColumn("IsExchangeRate", GetType(Boolean)), New DataColumn("Details", GetType(String)), New DataColumn("Marked", GetType(Boolean)), New DataColumn("Ignore", GetType(Boolean))})
    dt.Rows.Add(1, "111", "01/02/2018", "BN", "123455AAA", "CM", 124, "GA", 100, 5, True, "Details", True, True)
    dt.Rows.Add(2, "222", "02/02/2018", "BN1", "123455AAA112", "CM1", 12411, "GA1", 200, 6, True, "Details", True, False)
    gvtfaTransaction.DataSource = dt
    gvtfaTransaction.DataBind()
End Sub

Private Sub BindDummyRow()
    Dim dummy As DataTable = New DataTable()
    dummy.Columns.Add("CustomerId")
    dummy.Columns.Add("Name")
    dummy.Columns.Add("Country")
    dummy.Rows.Add()
    gvtfaDetails.DataSource = dummy
    gvtfaDetails.DataBind()
End Sub

Protected Sub Ignore_Click(ByVal sender As Object, ByVal e As EventArgs)
End Sub

<WebMethod()>
Public Shared Function GetData(ByVal custid As Integer) As String
    Dim strconstr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(strconstr)
        Using cmd As SqlCommand = New SqlCommand("SELECT * FROM Customers WHERE CustomerId=@CustomerId", con)
            cmd.Parameters.AddWithValue("@CustomerId", custid)
            Using da As SqlDataAdapter = New SqlDataAdapter(cmd)

                Using ds As DataSet = New DataSet()
                    da.Fill(ds)
                    Return ds.GetXml()
                End Using
            End Using
        End Using
    End Using
End Function

<WebMethod()>
Public Shared Function Mark(ByVal id As Integer, ByVal Marked As String, ByVal LabelFullname As String) As String
    Try
        Dim age As Integer = Integer.Parse("1")
        Return "success"
    Catch ex As Exception
        Return "failed"
    End Try
End Function

Protected Sub gvtfaTrust_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then

        If e.Row.Cells(11).Controls.OfType(Of CheckBox)().FirstOrDefault().Checked Then
            e.Row.Cells(7).Controls.OfType(Of DropDownList)().FirstOrDefault().Enabled = False
            e.Row.Cells(7).Controls.OfType(Of DropDownList)().FirstOrDefault().Visible = True
            e.Row.Cells(7).Controls.OfType(Of Label)().FirstOrDefault().Visible = True
            e.Row.Cells(9).Controls.OfType(Of TextBox)().FirstOrDefault().Enabled = False
            e.Row.Cells(12).Controls.OfType(Of CheckBox)().FirstOrDefault().Enabled = False
        End If
    End If
End Sub

Screenshot