How To Restrict the number of rows in a dataview when binding to a GridView


In this post i will show how to restrict the number of items bound to an asp:GridView. Basically I never wanted more than 10 items to be displayed.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RestrictNumRows.aspx.cs"
Inherits="RestrictNumRows" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="Server">
</asp:GridView>
</div>
</form>
</body>
</html>




using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class RestrictNumRows : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{

FilterRows obj = new FilterRows(GetDataSet().DefaultView,2);
GridView1.DataSource = obj;
GridView1.DataBind();
}

}
public class FilterRows : IEnumerable
{
DataView dataView;
private int rowsToShow;

public FilterRows(DataView dataView, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.dataView = dataView;
}

public IEnumerator GetEnumerator()
{
return new PageOfData(this.dataView.GetEnumerator(), this.rowsToShow);
}


internal class PageOfData : IEnumerator
{
private IEnumerator e;
private int cnt = 0;
private int rowsToShow;

internal PageOfData(IEnumerator e, int rowsToShow)
{
this.rowsToShow = rowsToShow;
this.e = e;
}

public object Current
{
get { return e.Current; }
}

public bool MoveNext()
{
// If we've hit out limit return false
if (cnt >= rowsToShow)
return false;

// Track the current row
cnt++;

return e.MoveNext();
}

public void Reset()
{
e.Reset();
cnt = 0;
}
}
}
public DataTable GetDataSet()
{

DataTable dt = new DataTable("Company");
DataRow dr;
dt.Columns.Add(new DataColumn("Id", typeof(Int32)));
dt.Columns.Add(new DataColumn("IntField", typeof(Int32)));
dt.Columns.Add(new DataColumn("StringField", typeof(string)));
for (int i = 1; i <= 20; i++)
{
dr = dt.NewRow();
dr[0] = i;
dr[1] = i;
dr[2] = "Company" + i + Environment.NewLine + "Title" + i;
dt.Rows.Add(dr);
DataColumn[] Parent_PKColumns = new DataColumn[1];
Parent_PKColumns[0] = dt.Columns["ID"];
dt.PrimaryKey = Parent_PKColumns;
Session["DataSource"] = dt;
}

return dt;
}

}

No comments:

Post a Comment