Insert Row in nested ASP.Net GridView without PostBack using C# and VB.Net

Last Reply 9 days ago By pandeyism

Posted 13 days ago

Is it possible to dynamically add a row to a nested gridview (childgrid) via an "add" button so the page does not require a refresh?

I seem to be able to do it in a regular grid, but I cannot do so in the nested grid. 

<asp:GridView ID="gvTrust" runat="server" AutoGenerateColumns="false" AllowPaging="True" PageSize="20" OnPageIndexChanging="OnPageIndexChanging" AllowSorting="True" OnSorting="OnSorting" CssClass="table table-striped table-bordered table-hover" DataKeyNames="ID" OnRowDataBound="OnRowDataBound" Width="98%" HorizontalAlign="Center">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <img alt="" style="cursor: pointer" src="images/plus.png" id="Expand" />                
                <asp:Panel ID="pnlLoan" runat="server" Style="display: none">
                    <asp:GridView ID="gvLoan" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" ShowFooter="True" CssClass="ChildGrid table table-striped table-bordered table-hover">
                        <Columns>                            
                            <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" 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="true" 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"/>
                                </ItemTemplate>
                            </asp:TemplateField>
                        </Columns>
                     </asp:GridView>
                </asp:Panel>
            </ItemTemplate>
        </asp:TemplateField>           
            <asp:BoundField DataField="EntryType" HeaderText="7. Entry Type" HeaderStyle-Wrap="false" SortExpression="EntryType" />
            <asp:TemplateField HeaderText="8. 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" CssClass="selectpicker show-tick form-control Update" data-style="btn btn-default btn-sm" data-live-search-style="true" data-live-search="true"/>
                </ItemTemplate>
                <HeaderStyle HorizontalAlign="Left" Wrap="false" />
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

JS    

    <script type="text/javascript">      
        $("[src*=plus]").live("click", function () {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("src", "images/minus.png");
        });

        $("[src*=minus]").live("click", function () {
            $(this).attr("src", "images/plus.png");
            $(this).closest("tr").next().remove();
        });
    </script>

 

Posted 9 days ago Modified on 5 days ago

Hey Warren,

Use UpdatePanel for partial post back the page to display the inserted record. Please refer below sample.

HTML

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("[src*=plus]").live("click", function () {
        $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
        $(this).attr("src", "images/minus.png");
    });
    $("[src*=minus]").live("click", function () {
        $(this).attr("src", "images/plus.png");
        $(this).closest("tr").next().remove();
    });
</script>
<asp:ScriptManager runat="server" />
<asp:UpdatePanel runat="server" ID="updatePanel" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" CssClass="Grid"
            DataKeyNames="CustomerID" OnRowDataBound="OnRowDataBound">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <img alt="" style="cursor: pointer" src="images/plus.png" id="imgdiv<%# Eval("CustomerID") %>" />
                        <asp:Panel ID="pnlOrders" runat="server" Style="display: none">
                            <asp:GridView ID="gvOrders" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid"
                                DataKeyNames="CustomerID" ShowFooter="true" PageSize="3" AllowPaging="true" OnPageIndexChanging="gvOrders_OnPageIndexChanging">
                                <Columns>
                                    <asp:TemplateField HeaderText="Freight">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtFreight" runat="server" Text='<%#Eval("Freight") %>' />
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtFreight1" runat="server" Text='<%#Eval("Freight") %>' />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="OrderDate">
                                        <ItemTemplate>
                                            <asp:TextBox ID="txtDate" runat="server" Text='<%#Eval("OrderDate") %>' />
                                        </ItemTemplate>
                                        <FooterTemplate>
                                            <asp:TextBox ID="txtDate1" runat="server" Text='<%#Eval("OrderDate") %>' />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                    <asp:TemplateField HeaderText="Add">
                                        <FooterTemplate>
                                            <asp:LinkButton ID="LinkButton1" Text="Add" OnClick="AddRows" runat="server" />
                                        </FooterTemplate>
                                    </asp:TemplateField>
                                </Columns>
                            </asp:GridView>
                        </asp:Panel>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="CustomerId">
                    <ItemTemplate>
                        <asp:TextBox ID="txtCustomerId" runat="server" Text='<%#Eval("CustomerId") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="ContactName">
                    <ItemTemplate>
                        <asp:TextBox ID="txtName" runat="server" Text='<%#Eval("ContactName") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="City">
                    <ItemTemplate>
                        <asp:TextBox ID="txtCity" runat="server" Text='<%#Eval("City") %>' />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Update">
                    <ItemTemplate>
                        <asp:Button Text="Update" runat="server" ID="btnUpdate" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </ContentTemplate>
</asp:UpdatePanel>

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;

VB.Net

Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        gvCustomers.DataSource = GetData("select top 3 * from Customers");
        gvCustomers.DataBind();
    }
}

private static DataTable GetData(string query)
{
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand())
        {
            cmd.CommandText = query;
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataSet ds = new DataSet())
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string customerId = gvCustomers.DataKeys[e.Row.RowIndex].Value.ToString();
        GridView gvOrders = e.Row.FindControl("gvOrders") as GridView;
        gvOrders.DataSource = GetData(string.Format("select * from Orders where CustomerId='{0}'", customerId));
        gvOrders.DataBind();
    }
}

protected void Change(object sender, EventArgs e)
{
    GridViewRow row = (sender as TextBox).NamingContainer as GridViewRow;
    string Freight = (row.FindControl("txtFreight") as TextBox).Text;
    string orderdate = (row.FindControl("txtDate") as TextBox).Text;
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("UPDATE Orders SET OrderDate = @OrderDate WHERE Freight = @Freight", con))
        {
            cmd.Parameters.AddWithValue("@Freight", Freight.Split(',')[Freight.Split(',').Length - 1]);
            cmd.Parameters.AddWithValue("@OrderDate", orderdate.Split(',')[orderdate.Split(',').Length - 1]);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

protected void gvOrders_OnPageIndexChanging(object sender, GridViewPageEventArgs e)
{
    GridView gvOrders = (sender as GridView);
    gvOrders.PageIndex = e.NewPageIndex;
    gvOrders.DataSource = GetData(string.Format("select * from Orders where CustomerId='{0}'", gvOrders.DataKeys[0].Value));
    gvOrders.DataBind();
    string id = "imgdiv" + gvOrders.DataKeys[0].Value;
    string script = @"$(document).ready(function () {$('#" + id + "').trigger('click');});";
    ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "alert", script, true);
}

protected void AddRows(object sender, EventArgs e)
{
    GridViewRow row = (sender as LinkButton).NamingContainer as GridViewRow;
    string customerId = this.gvCustomers.DataKeys[((row.NamingContainer as GridView).NamingContainer as GridViewRow).RowIndex].Value.ToString();

    string Freight = (row.FindControl("txtFreight1") as TextBox).Text.Trim().Replace(",", "");
    string orderDate = (row.FindControl("txtDate1") as TextBox).Text.Trim().Replace(",", "");
    string strConnString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlCommand cmd = new SqlCommand("INSERT INTO Orders(CustomerId,Freight,OrderDate) VALUES(@CustomerId,@Freight,@OrderDate)", con))
        {
            cmd.Parameters.AddWithValue("@CustomerId", customerId);
            cmd.Parameters.AddWithValue("@Freight", Freight);
            cmd.Parameters.AddWithValue("@OrderDate", orderDate);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
    (row.FindControl("txtDate1") as TextBox).Text = orderDate;
    (row.FindControl("txtFreight1") as TextBox).Text = Freight;
    string id = "imgdiv" + customerId;
    string script = @"$(document).ready(function () {$('#" + id + "').trigger('click');});";
    ScriptManager.RegisterClientScriptBlock(sender as Control, this.GetType(), "alert", script, true);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not IsPostBack Then
        gvCustomers.DataSource = GetData("select top 3 * from Customers")
        gvCustomers.DataBind()
    End If
End Sub

Private Shared Function GetData(ByVal query As String) As DataTable
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(strConnString)
        Using cmd As SqlCommand = New SqlCommand()
            cmd.CommandText = query
            Using sda As SqlDataAdapter = New SqlDataAdapter()
                cmd.Connection = con
                sda.SelectCommand = cmd
                Using ds As DataSet = New DataSet()
                    Dim dt As DataTable = New DataTable()
                    sda.Fill(dt)
                    Return dt
                End Using
            End Using
        End Using
    End Using
End Function

Protected Sub OnRowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
    If e.Row.RowType = DataControlRowType.DataRow Then
        Dim customerId As String = gvCustomers.DataKeys(e.Row.RowIndex).Value.ToString()
        Dim gvOrders As GridView = TryCast(e.Row.FindControl("gvOrders"), GridView)
        gvOrders.DataSource = GetData(String.Format("select * from Orders where CustomerId='{0}'", customerId))
        gvOrders.DataBind()
    End If
End Sub

Protected Sub Change(ByVal sender As Object, ByVal e As EventArgs)
    Dim row As GridViewRow = TryCast((TryCast(sender, TextBox)).NamingContainer, GridViewRow)
    Dim Freight As String = (TryCast(row.FindControl("txtFreight"), TextBox)).Text
    Dim orderdate As String = (TryCast(row.FindControl("txtDate"), TextBox)).Text
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(strConnString)
        Using cmd As SqlCommand = New SqlCommand("UPDATE Orders SET OrderDate = @OrderDate WHERE Freight = @Freight", con)
            cmd.Parameters.AddWithValue("@Freight", Freight.Split(","c)(Freight.Split(","c).Length - 1))
            cmd.Parameters.AddWithValue("@OrderDate", orderdate.Split(","c)(orderdate.Split(","c).Length - 1))
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using
End Sub

Protected Sub gvOrders_OnPageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    Dim gvOrders As GridView = (TryCast(sender, GridView))
    gvOrders.PageIndex = e.NewPageIndex
    gvOrders.DataSource = GetData(String.Format("select * from Orders where CustomerId='{0}'", gvOrders.DataKeys(0).Value))
    gvOrders.DataBind()
    Dim id As String = "imgdiv" & gvOrders.DataKeys(0).Value
    Dim script As String = "$(document).ready(function () {$('#" & id & "').trigger('click');});"
    ScriptManager.RegisterClientScriptBlock(TryCast(sender, Control), Me.[GetType](), "alert", script, True)
End Sub

Protected Sub AddRows(ByVal sender As Object, ByVal e As EventArgs)
    Dim row As GridViewRow = TryCast((TryCast(sender, LinkButton)).NamingContainer, GridViewRow)
    Dim customerId As String = Me.gvCustomers.DataKeys((TryCast((TryCast(row.NamingContainer, GridView)).NamingContainer, GridViewRow)).RowIndex).Value.ToString()
    Dim Freight As String = (TryCast(row.FindControl("txtFreight1"), TextBox)).Text.Trim().Replace(",", "")
    Dim orderDate As String = (TryCast(row.FindControl("txtDate1"), TextBox)).Text.Trim().Replace(",", "")
    Dim strConnString As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
    Using con As SqlConnection = New SqlConnection(strConnString)
        Using cmd As SqlCommand = New SqlCommand("INSERT INTO Orders(CustomerId,Freight,OrderDate) VALUES(@CustomerId,@Freight,@OrderDate)", con)
            cmd.Parameters.AddWithValue("@CustomerId", customerId)
            cmd.Parameters.AddWithValue("@Freight", Freight)
            cmd.Parameters.AddWithValue("@OrderDate", orderDate)
            con.Open()
            cmd.ExecuteNonQuery()
            con.Close()
        End Using
    End Using

        TryCast(row.FindControl("txtDate1"), TextBox).Text = orderDate
        TryCast(row.FindControl("txtFreight1"), TextBox).Text = Freight
    Dim id As String = "imgdiv" & customerId
    Dim script As String = "$(document).ready(function () {$('#" & id & "').trigger('click');});"
    ScriptManager.RegisterClientScriptBlock(TryCast(sender, Control), Me.[GetType](), "alert", script, True)
End Sub

Screenshot