如何仅更新子GridView?

时间:2012-03-31 06:20:55

标签: c# asp.net gridview

这就是我现在正在做的事情:

<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();
}

所以,在按钮上点击GridView1我正在更新数据库并同时获取数据,这没有任何问题。但为此,我必须绑定/刷新父(GridView1)Gridview这个过程相当慢,因为有近50行。我正在寻找的是什么; 我想仅更新或刷新GridView2以显示添加的评论。

6 个答案:

答案 0 :(得分:1)

GridView1.RowCommand是处理按钮操作的正确事件。

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();
    };

在此事件(或其他事件)上,父项不会绑定,除非您指定它。 每次页面加载时,绑定控件的一个常见原因是错误地调用DataBind()。为了防止这种情况,需要在页面的第一个请求上进行绑定,正确的方法是检查IsPostBack是否为假。

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

答案 1 :(得分:0)

您只能刷新子网格视图而不刷新父网格视图。 为此,您可以对客户端单击(ClientClick)按钮并调用jquery函数,而不是服务器端单击。 然后,您可以通过ajax调用从特定的jquery函数调用Web方法或http处理程序类,仅更新子gridview中的项目。 在这里,您的父网格将不会刷新,因为按钮单击时没有服务器命中。 希望这会有所帮助,如果您需要,我将提供jquery函数的示例代码。

答案 2 :(得分:0)

试试这个

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();

}

答案 3 :(得分:0)

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>

代码背后

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() 
}

注意 - 将ScrapID DataItem转换为DataKey

答案 4 :(得分:0)

我会设置按钮的命令名,然后使用gridview的OnRowCommand事件

<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>

代码背后:

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
    }
  }

从内存中执行此操作可能不准确,但应该足够接近,以便了解去哪里

答案 5 :(得分:0)

仅更新/刷新单击“更新”按钮的行中的子GridView2

首先,你需要将整个GridView1放在更新面板中。 而另一个UpdatePanel里面的子GridView 然后在按钮上单击U以保存您的数据并刷新子网格,这样只会刷新子网格。

这是一个有效的例子。

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();
        }


    } 

}

}

背后的代码

<%@ 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>