Ashwini Verma
Ashwini Verma

Reputation: 7525

how to update only child GridView?

here is what I'm doing right now:

<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridViewUserScraps_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                 <asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
                 <asp:Button ID="btnPost" Text="Comment" runat="server" CommandName="Comment"  CommandArgument='<%#Eval("ScrapId")%>' />
                <asp:GridView ID="GridView2" runat="server">
                   <%--this GridView2 showing comments--%>
                </asp:GridView>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

protected void GridViewUserScraps_RowDataBound(object sender, GridViewRowEventArgs e)
{
    GridView gv = new GridView();
    gv = (GridView)row.FindControl("GridView2");
    //getting data to bind child gridview.
    gv.DataSource = td;
    gv.DataBind();
}

so, on button click of the GridView1 I'm updating database and fetching data at same time, there is no any problem in that. But for this I have to Bind/refresh parent(GridView1) Gridview which quite slow process as there are almost 50 rows. what I'm looking is; I want to update or refresh only GridView2 to be shown added comments.

Upvotes: 2

Views: 3438

Answers (6)

Vipresh
Vipresh

Reputation: 1307

To Update /refresh only the Child GridView2 in the row where the Update button has been clicked

First of all U need to place the entire GridView1 in Update Panel. And the child GridView inside another UpdatePanel Then on the button click U just hav to save ur data and refresh the child grid , in this way only the child grid will be refreshed.

heres a working example.

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
            SqlCommand cmd = new SqlCommand("select top 10 * from orders", conn);
            cmd.Connection.Open();
            var dt = cmd.ExecuteReader();
            GridView1.DataSource = dt;
            GridView1.DataBind();
            cmd.Connection.Close();
            cmd.Dispose();
        }

    }

    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "UpdateChildGrid")
        {

            GridViewRow row = (e.CommandSource as Button).NamingContainer as GridViewRow;
            GridView child = row.FindControl("GridView2") as GridView;

            string id = row.Cells[0].Text;

            SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
            SqlCommand cmd = new SqlCommand("select top 5 * from [order Details] where OrderID = " + id, conn);
            cmd.Connection.Open();
            var dt = cmd.ExecuteReader();
            child.DataSource = dt;
            child.DataBind();
            cmd.Connection.Close();
            cmd.Dispose();
        }
    }



    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            string id = e.Row.Cells[0].Text;
            GridView gv = new GridView();
            gv = (GridView)e.Row.FindControl("GridView2");
            SqlConnection conn = new SqlConnection("Password=password;Persist Security Info=True;User ID=uid;Initial Catalog=Northwind;Data Source=servername");
            SqlCommand cmd = new SqlCommand("select top 5 * from [order Details] where OrderID = " + id, conn);
            cmd.Connection.Open();
            var dt = cmd.ExecuteReader();
            gv.DataSource = dt;
            gv.DataBind();
            cmd.Connection.Close();
            cmd.Dispose();
        }


    } 

}

}

And code behind

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>


<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
    <p>

    To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
</p>
<p>
    You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409"
        title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
</p>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>
    <asp:GridView ID="GridView1" runat="server" 
    onselectedindexchanged="GridView1_SelectedIndexChanged" 
    AutoGenerateColumns="False" 
    onrowcommand="GridView1_RowCommand" onrowdatabound="GridView1_RowDataBound">
    <Columns>
        <asp:BoundField DataField="OrderID"  />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:UpdatePanel ID="UpdatePanel2" runat="server">
                <ContentTemplate>
                    <asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox> 
                    <asp:Button ID="btnPost" ButtonType="Button" Text="Comment" runat="server" CommandName="UpdateChildGrid" />
                    <asp:GridView ID="GridView2" runat="server"> 
                    </asp:GridView> 
                </ContentTemplate>
                </asp:UpdatePanel>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

</asp:GridView>
</ContentTemplate>

</asp:UpdatePanel>
</asp:Content>

Upvotes: 0

Pankaj
Pankaj

Reputation: 10105

GridView HTML

<asp:gridview id="GridView1" runat="server" onrowdatabound="GridViewUserScraps_RowDataBound">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
                <asp:Button ID="btnPost" Text="Comment" runat="server" OnClick="btnPost_Click" />
                <asp:GridView ID="GridView2" runat="server">
                    <%--this GridView2 showing comments--%>
                </asp:GridView>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:gridview>

Code Behind

protected void btnPost(object sender, EventArgs e)
{
    //Your code for other operations
    //
    GridView GridView2 = (GridView)((GridViewRow)((Button)sender).NamingContainer).FindControl("GridView2");
    GridView2.DataSource = YourDataBasefetchingFunction();
    GridView2.DataBind() 
}

Note - Convert the ScrapID DataItem into the DataKey

Upvotes: 0

JCherryhomes
JCherryhomes

Reputation: 426

I would set the commandname of the button then use the gridview's OnRowCommand event

<asp:gridview id="GridView1" runat="server" onrowdatabound="GridViewUserScraps_RowDataBound" OnRowCommand="GridView1_RowCommand">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:TextBox ID="MakeComments" runat="server" TextMode="MultiLine"></asp:TextBox>
            <asp:Button ID="btnPost" Text="Comment" runat="server" CommandName="UpdateChildGrid" />
            <asp:GridView ID="GridView2" runat="server">
                <%--this GridView2 showing comments--%>
            </asp:GridView>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

Code Behind:

protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
  {
    if(e.CommandName=="UpdateChildGrid")
    {
        GridViewRow row = (e.CommandSource as Button).NamingContainer as GridViewRow;
        GridView child = row.FindControl("GridView2") as GridView;
        // update child grid
    }
  }

Doing this from memory so it may not be exact, but should be close enough to give you an idea of where to go

Upvotes: 0

Adrian Iftode
Adrian Iftode

Reputation: 15663

The GridView1.RowCommand is the right event to handle the button's action.

GridView1.RowCommand += (o, e) =>
    {
        var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
        var makeComments = row.FindControl("MakeComments") as TextBox;
        int scrapId = Int32.TryParse((string)e.CommandArgument, out scrapId) ? scrapId : 0;
        var gridView2 = row.FindControl("GridView2") as GridView;

        ... place here the code which the comments

        gridView2.DataSource = GetCommentsByScrapId();
        gridView2.DataBind();
    };

On this event (or others), the parent won't bind, unless you specify it. One common reason the bind a control is by mistakenly call DataBind() every time when the page loads. To prevent this, it is needed to do the binding on the first request of the page and the proper way is to check if the IsPostBack is false.

protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                 GridView1.DataSource = GetUserScraps();
                 GridView1.DataBind();
            }
        }

Upvotes: 1

PraveenVenu
PraveenVenu

Reputation: 8337

Try this

foreach(GridViewRow rIndex in GridView1.Rows)
{

GridView gv = new GridView();
    gv = (GridView)row.FindControl("GridView2");
    //getting data to bind child gridview.
   // if you want to get the row key value use GridView1.DataKeys[rIndex.RowIndex].Value
    gv.DataSource = td;
    gv.DataBind();

}

Upvotes: 0

Sugandika
Sugandika

Reputation: 772

You can refresh only the child gridview without refreshing your parent gridview. To do it you can do a client side click (ClientClick) to the button and call a jquery function, instead of a server side click. Then you can update only the items in your child gridview, by calling a web method or http handler class from the particular jquery function via ajax call. Here your parent grid won't be refreshed since there is no server hit at the button click. Hope this helps and if you need I will provide sample code for the jquery function.

Upvotes: 0

Related Questions