Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Nevron Chart
Search :       Advanced Search »
Home » ASP.NET Controls » 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.

Page Views : 20661
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


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.

 

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate 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.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
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 | 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 | 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 | 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 | Modify 
Team Foundation Server Hosting
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.