Friday, April 30, 2010

Programmatically adding paging in Gridview - ASP.NET

 

In *.aspx page insert a gridview like this:

<asp:GridView ID="courseListGridView" runat="server" CssClass="gridViewStyle2" 
AllowPaging="True" PageSize="20"
onpageindexchanging="courseListGridView_PageIndexChanging">
<PagerSettings FirstPageText="First Page" LastPageText="Last Page"
Mode="NextPreviousFirstLast" NextPageText="Next Page"
PreviousPageText="Previous Page" />
</asp:GridView>


Then in the code behind add this code:


public void LoadAllCourses()
{
// Create MySql Connection
using (MySqlConnection conn = new MySqlConnection())
{
// Configure the connection from the web.config entry
conn.ConnectionString = ConfigurationManager.ConnectionStrings["eraConnectionString"].ConnectionString;

// SQL Command for GridView
string cmdText = "Select * from student.courseinfo";

// Set MySQL Command
MySqlCommand cmd = new MySqlCommand(cmdText, conn);
cmd.CommandType = CommandType.Text;

MySqlDataAdapter cmdAdapter = new MySqlDataAdapter();
cmdAdapter.SelectCommand = cmd;
// Create empty DataSet
DataSet resultsDS = new DataSet();
conn.Open();
cmdAdapter.Fill(resultsDS);
conn.Close();

courseListGridView.DataSource = resultsDS;
courseListGridView.DataBind();
}
}

protected void courseListGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
courseListGridView.PageIndex = e.NewPageIndex;
LoadAllCourses();

}

No comments:

Post a Comment