Click here to Skip to main content
6,292,811 members and growing! (10,447 online)
Email Password   helpLost your password?
Database » Database » SQL Server     Intermediate License: The Code Project Open License (CPOL)

Repeater within Gridview in C# ASP.NET 2.0

By Navin C. Pandit

This article discusses binding a gridview/repeater control from a dataset using a stored procedure
C#, ASP.NET, DBA, Dev
Posted:25 Jun 2008
Views:34,435
Bookmarked:21 times
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
7 votes for this article.
Popularity: 2.85 Rating: 3.38 out of 5
1 vote, 14.3%
1

2
3 votes, 42.9%
3
2 votes, 28.6%
4
1 vote, 14.3%
5

Introduction

Inserting a repeater within gridview is an easy task, but binding the headline in gridview and having data items correspond to the particular headline into a repeater, is a little bit tricky. Following a requirement I was given, I had to bind company name as a headline and the top four news of the company as data items under the headline. Then the next company name, and the top four news of that respective company and so on. Like this:

image001.jpg

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

Mechanism

Take a gridview control and set its AutoGenerateColumns="False". Put a label control within the grid to bind company name, so 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 a different ItemTemplate, then it will bind in another column, otherwise it will bind in the same column but in different rows as shown in the figure below. Now it is your choice, whether you are interested in binding in the same or a different column. Here, I have used a div tag, to separate company and their news rows. The div tag gives one more advantage. For example, we can apply CSS to a particular div for richer UI. The complete source code looks like this:

<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; we have to write some code in the code behind to get the data from the 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 dataset, with the column 'compname'. And finally, binding the data in data controls. The code looks like this:

protected void Page_Load(object sender, EventArgs e)
{
    binddata();
}

// Function to bind data in data controls..
public void binddata()
{
    // your connection string here
    string str = "Data Source=VS-NAVINCHANDRA\\SQLEXPRESS;" +
         "Initial Catalog=dbNavin;Integrated Security=SSPI"; 
    SqlConnection con = new SqlConnection(str);
    DataSet ds = new DataSet();
    // name of your stored procedure,
    SqlDataAdapter da = new SqlDataAdapter("getCompNews", con); 
    da.Fill(ds);

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

On clicking the ‘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 the 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've mentioned, because I've used a stored procedure 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 a stored procedure instead of using a direct SQL query. Of course a stored procedure is much better than a query, so I recommend going for the stored procedure.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Navin C. Pandit


Member
Working as Sr. Software Engineer
Occupation: Software Developer (Senior)
Location: India India

Other popular Database articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 5 of 5 (Total in Forum: 5) (Refresh)FirstPrevNext
GeneralVery Helpful Pinmemberdav0idz16:47 15 Apr '09  
GeneralRe: Very Helpful PinmemberNavin C. Pandit20:14 23 Apr '09  
QuestionHow do you display just the first 3 results ? PinmemberMayuresh8016:20 2 Nov '08  
AnswerRe: How do you display just the first 3 results ? PinmemberNavin C. Pandit21:30 19 Nov '08  
GeneralGood article PinmemberRajib Ahmed17:41 26 Jun '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 25 Jun 2008
Editor: Sean Ewington
Copyright 2008 by Navin C. Pandit
Everything else Copyright © CodeProject, 1999-2009
Web19 | Advertise on the Code Project