Nested user control to display relational record in page like nested GridView using C# and VB.Net in ASP.Net

Last Reply 2 months ago By Indresh

Posted 2 months ago

Hi

I have two tables that its names are user and detail_user and two tables has unique value (userId and managerCode).in my project, I have two User Controls that first UC in Defualt.aspx  show number of users from user table with a button that will show number of  detail of every users and this button connect to second UC that show detail of user from detail_user table.

Tip:userId change for every users and managerCode is Unchanged in two table.

how can show detail of every user in second UC when Click on button؟ 

Posted 2 months ago Modified on 2 months ago

Hi jimcode,

I have created sample code which full-fill your requirement. So Please refer the below code.

HTML

<div>
    <Uc:ucUsers ID="ucUsersData" runat="server" />
</div>

and you need to Register the user control on top of the aspx page.

<%@ Register TagPrefix="Uc" Src="~/Users.ascx" TagName="ucUsers" %>

Web User Control

Users.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="Users.ascx.cs" Inherits="Users" %>
<%@ Register TagPrefix="childUc" Src="~/UserDetails.ascx" TagName="ucUserDetails" %>
<style type="text/css">
    body
    {
        font-family: Arial;
        font-size: 10pt;
    }
    table
    {
        border: 1px solid #ccc;
    }
    table th
    {
        background-color: #F7F7F7;
        color: #333;
        font-weight: bold;
    }
    table th, table td
    {
        padding: 5px;
        border-color: #ccc;
    }
</style>
<script type="text/javascript" src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $("[id*=btnshow]").live("click", function () {
        if ($(this).attr("value") == "Show") {
            $(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>")
            $(this).attr("value", "Hide");
            $(this).attr("class", "btn btn-primary");
        }
        else {
            $(this).attr("text", "Show");
            $(this).closest("tr").next().remove();
            $(this).attr("value", "Show");
            $(this).attr("class", "btn btn-success");
        }
        return false;
    });
  
</script>
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" CssClass="Grid"
    DataKeyNames="CustomerID" OnRowDataBound="OnRowDataBound">
    <Columns>
        <asp:TemplateField HeaderText="Action">
            <ItemTemplate>
                <asp:Button ID="btnshow" Text="Show" class="btn btn-success" runat="server" />
                <asp:Panel ID="Panel1" runat="server" Style="display: none">
                    <childUc:ucUserDetails ID="UserDetails" runat="server" />
                </asp:Panel>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField ItemStyle-Width="150px" DataField="ContactName" HeaderText="Contact Name" />
        <asp:BoundField ItemStyle-Width="150px" DataField="City" HeaderText="City" />
    </Columns>
</asp:GridView>

C#

private string constring = ConfigurationManager.ConnectionStrings["constring"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.PopulateUsers();
    }
}

private void PopulateUsers()
{
    SqlConnection con = new SqlConnection(constring);
    SqlCommand cmd = new SqlCommand("Select TOP 10 CustomerId,ContactName,City  From Customers", con);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    gvUsers.DataSource = dt;
    gvUsers.DataBind();
}

protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        string customerId = gvUsers.DataKeys[e.Row.RowIndex].Value.ToString();
        ((e.Row.FindControl("UserDetails") as UserControl).FindControl("gvUserDetails") as GridView).DataSource = GetChildData(customerId);
        ((e.Row.FindControl("UserDetails") as UserControl).FindControl("gvUserDetails") as GridView).DataBind();
    }
}

private DataTable GetChildData(string userId)
{
    SqlConnection con = new SqlConnection(constring);
    SqlCommand cmd = new SqlCommand("Select * From Customers Where CustomerId=@CustomerId", con);
    cmd.Parameters.AddWithValue("@CustomerId", userId);
    SqlDataAdapter sda = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    sda.Fill(dt);
    return dt;
}

UserDetails.ascx

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="UserDetails.ascx.cs" Inherits="UserDetails" %>
<asp:GridView ID="gvUserDetails" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                Address:<asp:Label ID="lblAddress" Text='<%#Eval("Address")%>' runat="server" />
                PostalCode:<asp:Label ID="lblPostalCode" Text='<%#Eval("PostalCode")%>' runat="server" />
                Phone:<asp:Label ID="lblPhone" Text='<%#Eval("Phone")%>' runat="server" />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

Vb.Net

Private constring As String = ConfigurationManager.ConnectionStrings("constring").ConnectionString
Protected Sub Page_Load(sender As Object, e As EventArgs)
	If Not IsPostBack Then
		Me.PopulateUsers()
	End If
End Sub

Private Sub PopulateUsers()
	Dim con As New SqlConnection(constring)
	Dim cmd As New SqlCommand("Select TOP 10 CustomerId,ContactName,City  From Customers", con)
	Dim sda As New SqlDataAdapter(cmd)
	Dim dt As New DataTable()
	sda.Fill(dt)
	gvUsers.DataSource = dt
	gvUsers.DataBind()
End Sub

Protected Sub OnRowDataBound(sender As Object, e As GridViewRowEventArgs)
	If e.Row.RowType = DataControlRowType.DataRow Then
		Dim customerId As String = gvUsers.DataKeys(e.Row.RowIndex).Value.ToString()
		TryCast(TryCast(e.Row.FindControl("UserDetails"), UserControl).FindControl("gvUserDetails"), GridView).DataSource = GetChildData(customerId)
		TryCast(TryCast(e.Row.FindControl("UserDetails"), UserControl).FindControl("gvUserDetails"), GridView).DataBind()
	End If
End Sub

Private Function GetChildData(userId As String) As DataTable
	Dim con As New SqlConnection(constring)
	Dim cmd As New SqlCommand("Select * From Customers Where CustomerId=@CustomerId", con)
	cmd.Parameters.AddWithValue("@CustomerId", userId)
	Dim sda As New SqlDataAdapter(cmd)
	Dim dt As New DataTable()
	sda.Fill(dt)
	Return dt
End Function

Screenshot

 

I agree, here is the link: https://www.e-iceblue.com/Introduce/spire-office-for-net-free.html