Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » ASP.NET & Web Forms » Repeater within ASP.NET 2.0 Gridview

Repeater within ASP.NET 2.0 Gridview

This article demonstrates how to bind a repeater control within a GridView control having a relation between the GridView and Repeater data.

Total page views :  10834
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Introduction

           

This article and code snippet here shows how to bind a repeater control and Gridview control to a relational data so the GridView and the Repeater control show related data.

 

Inserting a Repeater within Gridview is an easy task but to bind the headline in the GridViewand data items correspond to the particular head line into a Repeater control is a little bit trickier job. According to a requirement, I have to bind company name as headline and top four news of the company as its data items under the headline, again next company name and top four news of respective company and so on.

 

Here, I have to use a repeater control to bind news while I am binding company name in grid view. We can also make the company name as link button which on click, will navigate to corresponding page. For this we have to pass navigate URL for a company dynamically. We can do this by writing code in OnRowDataBound event of gridview. We can also make news row as link.

 

 

Mechanism

           

Take a GridView control and set its AutoGenerateColumns="False".  Put a label control within the GridView to bind company name. You can also use its BoundField.

 

Now, within the same ItemTemplate, place a repeater control and put one more label control within this repeater control to bind news of respective company. If you are using different ItemTemplate, then it will bind in another column, otherwise it will bind in the same column but in different rows as shown in fig. below.

 

Now it is your choice, whether you are interested to bind in same or different column. Here, I have used div tag, to separate company and their news rows. The div tag gives one more advantage i.e. we can apply CSS to a particular div for richer UI.

 

The complete source code is here.

           

            <div style="width:400px; font-family:Arial; font-size:small">

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%" GridLines="None">

            <Columns>

                <asp:TemplateField>

                <ItemTemplate>

                    <div style="color:Blue;font-weight:bold">

                        <asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"compname") %>'></asp:Label>

                    </div>

                    <asp:Repeater ID="Repeater1" runat="server" DataSource='<%#DataBinder.Eval(Container, "DataItem.InnerVal") %>'>

                    <ItemTemplate>

                    <div style="padding-left:20px; padding-top:5px">

                        <asp:Label ID="Label2" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"news") %>'></asp:Label>

                    </div>

                   

                    </ItemTemplate>

                    </asp:Repeater>

                    <div style="text-align:right">

                        <asp:HyperLink ID="link" runat="server">More</asp:HyperLink>

                    </div>

                </ItemTemplate>

                </asp:TemplateField>

            </Columns>

        </asp:GridView>

    </div>

 

 

It is obvious that we have to write some code in code behind to get the data from database.

I have used a stored procedure that returns two tables, i.e. for company name and news section.

 

Now I am making a relation between these two tables in a DataSet, with column 'compname'.  And finally, binding the data in data controls.

 

Here is the code on the page load event handler. As you can see from the binddat method, I get data in a DataSet from the database, sets a relation and sets the DataSource property of the GridView control to the DataSet. Rest data binding is done in the above ASP.NET code.

 

       protected void Page_Load(object sender, EventArgs e)

    {

        binddata();

    }

 

    // Function to bind data in data controls..

    public void binddata()

    {

        string str = "Data Source=VS-NAVINCHANDRA\\SQLEXPRESS;Initial Catalog=dbNavin;Integrated Security=SSPI"; // your connection string here

        SqlConnection con = new SqlConnection(str);

        DataSet ds = new DataSet();

        SqlDataAdapter da = new SqlDataAdapter("getCompNews", con); // name of your stored procedure,

        da.Fill(ds);

 

        ds.Relations.Add("InnerVal", ds.Tables[0].Columns["compname"], ds.Tables[1].Columns["compname"]);   // making a relation between two tables.

        GridView1.DataSource = ds.Tables[0];

        GridView1.DataBind();

    }

 

           

On clicking 'More' link button, it should redirect to page which shows all the news of that particular company. So, we have to set NavigateUrl property for this control dynamically. To do this, write the code given below. As I have passed company name in query string, you can very easily access respective company data from your table to display.

 

 

            protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)

    {

        if (e.Row.RowType == DataControlRowType.DataRow)

        {

            HyperLink lnkMore = (HyperLink)e.Row.FindControl("link");

            Label lbl=(Label)e.Row.FindControl("Label1");

            lnkMore.NavigateUrl = "~/Company.aspx?cmp="+lbl.Text;

        }

    }

 

 

As I have mentioned for stored procedure, so you must create a stored procedure that returns tables. If you don't want to create it, just copy and paste the stored procedure given below and compile it. Make sure that your database contains all tables and respective columns.

 

            Create Procedure [dbo].[getCompNews]

 

as

begin

create table #Temp

(

compname varchar(50),

news varchar(150)

)

 

Insert into #Temp

select a.compname, b.news from Company as a

inner join  CompNews as b on a.CompId=b.CompId order by compname

 

 

Select distinct compname from #Temp

select * from #Temp

end

drop table #Temp

 

Here I am using stored procedure instead of using direct sql query. Offcourse a stored procedure is much better than a query.

 

 


Login to add your contents and source code to this article
 About the author
 
Navin Chandra
Navin Chandra
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
manipulate repeater controls from RowDataBound by Sean On January 20, 2009
Your row databound code works great for the gridview, but what if I want to drill into the repeater. For example, I want to conditionally set the navigate url property of a hyperlink in the repeater. Thanks
Reply | Email | Delete | Modify | 
Re: manipulate repeater controls from RowDataBound by Navin Chandra On January 21, 2009
Hello Dear,
You can manipulate your data, for this you have to code explicitly in ItemDataBound event of repeater control. To bind navigate url property for hyperlink, you may use this code:

protected void repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType = = ListItemType.Item || e.Item.ItemType = = ListItemType.AlternatingItem)
        {
            HyperLink hlnk = new HyperLink();
            hlnk = (HyperLink)e.Item.FindControl("hlnkId");
            hlnk.NavigateUrl = "~/navincp.aspx;
         }
    }

Hope it will help you.

-Navin C
Reply | Email | Delete | Modify | 
Re: Re: manipulate repeater controls from RowDataBound by Sean On January 21, 2009
Thanks for the help, but one more quick question.  The code behind event list does not create an event handler for the repeater control since it is nested within the gridview.  Do I have to create an event handler for the nested repeater before I can manipulate the hyperlink with your code?
Reply | Email | Delete | Modify | 
Re: Re: Re: manipulate repeater controls from RowDataBound by Navin Chandra On February 6, 2009
Hi,
you can do it by adding delegates for the control dynamically or any other way that supports bubble event.
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.