locked
How can I get the gridview data in user control (ascx) page from a parent page? RRS feed

  • Question

  • User-353733005 posted

    I want to get the gridview data in parent page from a user control (ascx) page. Can any one help me please. I don't understand how to do that.

    Monday, November 20, 2017 7:47 AM

Answers

  • User-707554951 posted

    Hi Shibly

    user control:

    <%@ Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="CaseTest.CaseTest.WebUserControl1" %>
    <p> GridView control in user control</p>
    <asp:GridView ID="GridView1" runat="server"></asp:GridView>
    

    CodeBehind:

      protected void Page_Load(object sender, EventArgs e)
            {
                if (!this.IsPostBack)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                                new DataColumn("Name", typeof(string)),
                                new DataColumn("Country",typeof(string)) });
                    dt.Rows.Add(1, "John Hammond", "United States");
                    dt.Rows.Add(2, "Mudassar Khan", "India");
                    dt.Rows.Add(3, "Suzanne Mathews", "France");
                    dt.Rows.Add(4, "Robert Schidner", "Russia");
                    GridView1.DataSource = dt;
                    GridView1.DataBind();
                }
            }

    in page:

        <uc1:WebUserControl1 runat="server" id="WebUserControl1" />
            <asp:Button ID="Button1" runat="server" Text="Button"  OnClick="Button1_Click"/>

    Codebehind:

      protected void Button1_Click(object sender, EventArgs e)
            {
                GridView grid = (GridView)WebUserControl1.FindControl("GridView1");
                foreach(GridViewRow row in grid.Rows)
                {
                    Response.Write(row.Cells[0].Text.ToString()+"|");
                    Response.Write(row.Cells[1].Text.ToString() + "|");
                    Response.Write(row.Cells[2].Text.ToString() + "  <br />");
                }
            }

    Output:


    Best regards

    Cathy

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 20, 2017 9:03 AM