Gridview paging using Datatable - not working - c#

I have a gridview which has paging but when I click on Page 2 - page refreshes and returns the first page and the page link also remains on page 1.
Any help will be really appreciated :)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="Sequence" HeaderText="Sequence" HeaderStyle-
Width="10%"/>
<asp:TemplateField HeaderStyle-Width="90%">
<ItemTemplate>
<asp:Label ID="lblTitle" runat="server" Text='<%# Eval("Title") %>' Font-
Strikeout='<%# ((Convert.ToBoolean(Eval("Obsolete")))?true:false) %>' />
</ItemTemplate>
</asp:TemplateField>
Codebehind:-
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID,
_criteria.ParentGUID, _criteria.ShowObsolete);
GridView1.PageSize = 20;
ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
PageIndexChanging:-
public void GridView1_PageIndexChanging(object
sender,GridViewPageEventArgse)
{
GridView x = ((GridView)sender);
GridView1.DataSource = ViewState["dt_data"];
if (e.NewPageIndex > -1 && e.NewPageIndex <= x.PageCount)
{
x.PageIndex = e.NewPageIndex+1;
}
else
{
e.NewPageIndex--;
}
GridView1.DataBind();
}
Page Load:-
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BuildResults();
}
}

modify PageIndexChanging code
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgse)
{
GridView1.DataSource = (DataTable)ViewState["dt_data"];
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}

Set AllowPaging=”True” Properties of GridView to enable paging
Set PageSize property to mention how many records will be displayed on
each page.
HTML MARKUP :
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="20"
onpageindexchanging="GridView1_PageIndexChanging"
onrowcommand="GridView1_RowCommand" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
</asp:GridView>
private void BuildResults()
{
DataTable dt01 = obSectionDefinition.List(_criteria.AuditDefinitionGUID, _criteria.ParentGUID, _criteria.ShowObsolete);
// GridView1.PageSize = 20;
// ViewState["dt_data"] = dt01;
GridView1.DataSource = dt01;
GridView1.DataBind();
}
public void GridView1_PageIndexChanging(object sender,GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BuildResults();
}

I had a Response.Write on the page elsewhere and this was causing the paging to fail - removed it and this now works

Related

How can I highlight the current number in pagination - GridView PagerTemplate?

This is my current design in my GridView, the cells becomes orange on hover, this is achieved by using css. But my problem is how can I changed the cell background color if it is the one that is active?
Image: Current Design
HTML Code: (Only GridView)
<asp:GridView ID="GridView1" runat="server" PageSize="20" OnPageIndexChanging="GridView1_PageIndexChanging"
AllowPaging="True" OnDataBound="GridView1_DataBound"
Style="position: static">
<PagerSettings Position="Top" Mode="Numeric" />
<PagerStyle ForeColor="Black" HorizontalAlign="Center" Font-Underline="False" CssClass="pager" />
<PagerTemplate>
<table id="tablePager">
<tr style="background-color: #F8F8F8;">
<td>
<asp:LinkButton ID="First" CommandName="Page" CommandArgument="First" runat="server"
Text="<< First" Style="color: black" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="Previous" CommandName="Page" CommandArgument="Prev" runat="server"
Text="< Previous" Style="color: black" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
<asp:Repeater ID="Repeater1" runat="server" OnItemCommand="Repeater_ItemCommand" OnItemDataBound="Repeater_ItemDataBound" OnLoad="Repeater_Load">
<ItemTemplate>
<td id="cell">
<asp:LinkButton ID="lnkPageNumber" CommandName="Page" runat="server" ForeColor="Black" Font-Underline="False" />
</td>
</ItemTemplate>
</asp:Repeater>
<td>
<asp:LinkButton ID="Next" CommandName="Page" CommandArgument="Next" runat="server"
Text="Next >" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
<td>
<asp:LinkButton ID="Last" CommandName="Page" CommandArgument="Last" runat="server"
Text="Last >>" Style="color: black" ForeColor="Black" Font-Underline="False"></asp:LinkButton>
</td>
</tr>
</table>
</PagerTemplate>
</asp:GridView>
Code Behind:
Page Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGridView();
}
}
PopulateGridView
public void PopulateGridView()
{
String constring = System.Configuration.ConfigurationManager.ConnectionStrings["sqlconnect"].ToString();
MySqlConnection con = new MySqlConnection(constring);
using (MySqlCommand cmd = new MySqlCommand("SELECT * FROM tabletester"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
MySqlDataReader reader = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
con.Close();
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
Repeater_ItemCommand
protected void Repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "Page")
{
GridView1.PageIndex = Convert.ToInt32(e.CommandArgument);
GridView1.DataBind();
PopulateGridView();
}
}
Repeater_ItemDataBound
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
LinkButton lnkPageNumber = new LinkButton();
System.Int32 pageNumber = (System.Int32)e.Item.DataItem;
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
lnkPageNumber = (LinkButton)e.Item.FindControl("lnkPageNumber");
lnkPageNumber.Text = pageNumber.ToString();
lnkPageNumber.CommandArgument = (pageNumber - 1).ToString();
}
}
Repeater_Load
protected void Repeater_Load(object sender, EventArgs e)
{
Repeater Repeater = (Repeater)sender;
Repeater.DataSource = Enumerable.Range(1, GridView1.PageCount);
Repeater.DataBind();
}
You could do something like this in Repeater_ItemDataBound
if (e.Item.ItemIndex == GridView1.PageIndex)
{
lnkPageNumber.ForeColor = Color.Red;
}
That said, do you now a GridView has a build-in paging system? Much easier that the overly complex stuff you are doing. Below is all the code it takes:
ASPX
<asp:GridView ID="GridView1" runat="server" AllowPaging="true" PageSize="5"
OnPageIndexChanging="GridView1_PageIndexChanging"></asp:GridView>
CODE
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack == false)
{
BindDataToGridView();
}
}
private void BindDataToGridView()
{
GridView1.DataSource = source;
GridView1.DataBind();
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
BindDataToGridView();
}
This is IT. All the code you need for a functional paging system.

Gridview Paging ASP.NET with Pager Panel outside Gridview

This is my first time for using ASP.NET to develop website.
I want to show my data from database in a GridView with Paging function and I can implement it by using OnPageIndexChanging="GridView1_PageIndexChanging" but I want to use my own pager so the question is
"How can I link my pager (the right bottom in the pic) to the gridview instead the pager which generated by the ASP.NET"
Pics:
This is my code in aspx
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" CssClass="table table-bordered table-condensed table-striped table-primary table-vertical-center"
PageSize="3" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="UNIT_ID" HeaderText="รหัส" SortExpression="unitid">
<HeaderStyle CssClass="center" />
<ItemStyle Width="10%" CssClass="center" />
</asp:BoundField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Code in cs
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
bindGridView();
}
protected void bindGridView() {
string sqltxt = "select * from drug_units"; //where UNIT_ID =:unitid";
CommandData comm = new CommandData();
comm.SetCommandText(sqltxt);
//comm.AddInputParameter("unitid", "5");
List<DrugsUnit> dy = new List<DrugsUnit>();
comm.ExecuteNonQuery();
dy = comm.ExecuteToList<DrugsUnit>();
GridView1.DataSource = dy;
/*BoundField boundField = new BoundField();
boundField.DataField = "UNIT_ID";
boundField.HeaderText = "ID";
boundField.SortExpression = "ID";
boundField.HeaderStyle.CssClass = "center";
boundField.ItemStyle.CssClass = "center";
GridView1.Columns.Add(boundField);*/
GridView1.DataBind();
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
bindGridView();
}
}
protected void GridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
upGridPager.Update();
e.Row.SetRenderMethodDelegate(new RenderMethod((w, r) =>
{
e.Row.SetRenderMethodDelegate(null);
using (var ms = new StringWriter())
using (var writer = new HtmlTextWriter(ms))
{
e.Row.RenderControl(writer);
GridPager.InnerHtml = "<table>" + ms.ToString() + "</table>";
}
}));
}
The aspx could look like this (outside of your grid)
<asp:UpdatePanel ID="upGridPager" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<div runat="server" id="GridPager" />
</ContentTemplate>
</asp:UpdatePanel>

I want to do sorting on based on column of gridview, but event is not firing when I click on header of HeaderTemplete

I have created one gridview with custom column and want to perform sorting on them. When I click on column then no event is firing for sorting.
Below is the code which I have written
For .aspx page
<asp:GridView ID="grdConfigureCustomers" runat="server" AlternatingRowStyle- BackColor="Aqua" Width="1300px"
OnRowCommand="grdConfigureCustomers_RowCommand" OnRowEditing="grdConfigureCustomers_RowEditing"
OnRowUpdating="grdConfigureCustomers_RowUpdating" OnRowCancelingEdit="grdConfigureCustomers_RowCancelingEdit"
AutoGenerateColumns="false" AllowPaging="true" PageSize="5"
OnRowDeleting="grdConfigureCustomers_RowDeleting" ShowFooter="true"
onpageindexchanging="grdConfigureCustomers_PageIndexChanging" OnSorting="grdConfigureCustomers_Sorting" AllowSorting="true">
<HeaderStyle BackColor="AliceBlue" />
<Columns>
<asp:TemplateField HeaderText="Customer ID">
<ItemTemplate>
<asp:Label ID="lblCustomerId" runat="server" Text='<%# Eval("Customer_ID") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddCustomerId" runat="server"></asp:TextBox><span style="color:Red;">*</span>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
For .aspx.cs page
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadCustomerConfigurationGridView();
}
}
private void LoadCustomerConfigurationGridView()
{
DataTable dt = new DataTable();
dt = sqlHelper.GetCustomerListInformation();
grdConfigureCustomers.DataSource = dt;
grdConfigureCustomers.DataBind();
Session["data"] = dt;
}
private void LoadCustomerConfigurationGridView(string srtexpr, string direc)
{
DataTable dt = new DataTable();
dt = sqlHelper.GetCustomerListInformation();
DataView dv = new DataView(dt);
dv.Sort = srtexpr + " " + direc;
grdConfigureCustomers.DataSource = dv;
grdConfigureCustomers.DataBind();
Session["data"] = dt;
}
protected void grdConfigureCustomers_Sorting(object sender, GridViewSortEventArgs e)
{
switch (e.SortExpression)
{
case "DateLogged":
if (e.SortDirection == SortDirection.Ascending)
{
LoadCustomerConfigurationGridView("DateLogged", "ASC");
}
else
{
LoadCustomerConfigurationGridView();
}
break;
}
}
Please let me know what I missed for sorting. Thanks in advance.
You need to specify the SortExpression property in the TemplateField like this:
<asp:TemplateField HeaderText="Customer ID" SortExpression="Customer_ID">
You need to enable sorting. EnableSorting="true" in your asp.net:Gridview.

Add Data to gridview dynamically in ASp.net

I have a gridview
<asp:GridView ID="gvOrders" runat="server">
<Columns>
<asp:BoundField DataField="Item" HeaderText="Item" SortExpression="Item" />
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdnItemID" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Quantity" HeaderText="Quantity" SortExpression="Quantity" />
</Columns>
</asp:GridView>
.............................................
Now i want Add Rows to gridview with data getting from Textbox/DropdownList.
And then how to access this GridData rows.
Assuming your GridView datasource is a DataTable named Dtable;
DataRow row = new DataRow();
row["columnName"] = textBox1.Text;
DTable.Rows.Add(row);
gvOrders.DataSource=Dtable;
gvOrders.DataBind();
Please try this, how it will help you.
Aspx Page:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name"></asp:BoundField>
<asp:BoundField DataField="Number" HeaderText="Number" SortExpression="Number"></asp:BoundField>
</Columns>
</asp:GridView>
C# Code:
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt = new DataTable();
MakeDataTable();
}
else
{
dt = (DataTable)ViewState["DataTable"];
}
ViewState["DataTable"] = dt;
}
private void MakeDataTable()
{
dt.Columns.Add("Name");
dt.Columns.Add("Number");
}
protected void Button2_Click(object sender, EventArgs e)
{
AddToDataTable();
BindGrid();
}
private void AddToDataTable()
{
DataRow dr = dt.NewRow();
dr["Name"] = txtName.Text;
dr["Number"] = txtNumber.Text;
dt.Rows.Add(dr);
}
private void BindGrid()
{
GridView1.DataSource = dt;
GridView1.DataBind();
}

multiply the gridview columns

I will post you my code and i will explain what i want to do
<div>
<div>
<asp:GridView ID="gridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
<asp:HiddenField ID="hdValue" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div>
<asp:Button ID="btnMove" runat="server" Text="Add To Cart" OnClick="btnMove_Click" />
</div>
<div>
<asp:GridView ID="gridView2" runat="server">
<Columns>
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="tbQty" runat="server" Width="25px"
MaxLength="3" />
</ItemTemplate>
<ItemStyle Width="25px" HorizontalAlign="Center"/>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<br />
<asp:Button ID="Button1" runat="server" Text="Find the total" />
<asp:Label ID="Label7" runat="server" Text="Total"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" ontextchanged="TextBox1_TextChanged"></asp:TextBox>
<br />
<br />
</div>
and the theo.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class theo : System.Web.UI.Page
{
const string key = "MyDataSource5";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}
private void BindGridView()
{
if (Session[key] == null)
{
gridView1.DataSource = GetDataSource();
gridView1.DataBind();
}
else
{
gridView1.DataSource = (DataTable)Session[key];
gridView1.DataBind();
}
}
protected DataTable GetDataSource()
{
try
{
DataTable dt = new DataTable();
dt = new DataTable();
dt.Columns.Add("ID", typeof(int)).AutoIncrement = true;
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Price(Grouch)/Hectares", typeof(float));
DataColumn[] keys = new DataColumn[2];
keys[0] = dt.Columns["ID"];
dt.PrimaryKey = keys;
dt.Rows.Add("1", "Seaside Location", 1.5);
dt.Rows.Add("2", "Arable Land", 0.1);
dt.Rows.Add("3", "Foothills of the mountains", 1.5);
dt.Rows.Add("4", "Industrial Land", 0.1);
dt.Rows.Add("5", "Rolling Farmland", 0.5);
Session[key] = dt;
return dt;
}
catch
{
return null;
}
}
protected void btnMove_Click(object sender, EventArgs e)
{
try
{
DataTable dtMain = Session[key] as DataTable;
//copy the schema of source table
DataTable dtClone = dtMain.Clone();
foreach (GridViewRow gv in gridView1.Rows)
{
CheckBox chk = gv.FindControl("chkSelect") as CheckBox;
HiddenField hdValue = gv.FindControl("hdValue") as HiddenField;
if (chk.Checked)
{
//get only the rows you want
DataRow[] results = dtMain.Select("ID=" + hdValue.Value + "");
//populate new destination table
foreach (DataRow dr in results)
{
dtClone.ImportRow(dr);
}
}
gridView2.DataSource = dtClone;
gridView2.DataBind();
}
}
catch
{
BindGridView();
}
}
}
In this code when i check for example 2 choices from gridview 1 and click the button add to cart then these 2 choices are moving to the second gridview. As you see,I have a textbox for the quantity. I would like when i give the quantity to multiply it with the price.With the button 'find the total' i want to give me the result in the text box.How can i do that?
one simple solution may be useful to you.
protected void Button1_Click(object sender, EventArgs e)
{
int itemCount;
decimal itemPrice, itemTotal;
itemTotal = 0;
itemCount = 0;
itemPrice = 0;
foreach(GridViewRow gridView2Row in gridView2.Rows)
{
TextBox tbCount = gridView2Row.Cells[0].Controls[1] as TextBox;
itemCount = Convert.ToInt32(tbCount.Text);
itemPrice = Convert.ToDecimal(gridView2Row.Cells[3].Text);
itemTotal = itemTotal + (itemCount * itemPrice);
}
TextBox1.Text = itemTotal.ToString();
}

Categories

Resources