GridView client side paging not working - c#

Work with data from other program (for example in this code i use random number array - like query data from other program). Query it to DataTable and bind to GridView + adds for all rows delete button.
On delete button click - this button is inactive (use button.Enabled = false; and UpdatePanel so on buttons click i have "old" array all works great).
But when I use paging - I have "new" array for each time.
How to fix it? I need - in first page i click button - they became inactive, then I choose second page, then return in first page and see "old" array with inactive button.
aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.WebForm1" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="Up1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowDeleted="GridView1_RowDeleted"
OnRowDeleting="GridView1_RowDeleting" OnDataBinding="GridView1_DataBinding" AllowPaging="true" PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging">
<Columns>
<asp:BoundField DataField="Name" ItemStyle-Width="200px">
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Number" ItemStyle-Width="200px">
<ItemStyle Width="200px"></ItemStyle>
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Button ID="Button2" runat="server" Text="Button" onclick="Button2_Click" OnClientClick="return DeleteConfirm();" />
<asp:HiddenField ID="HiddenField2" runat="server" Value='<%# Bind("Name") %>' />
</ContentTemplate>
</asp:UpdatePanel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Reset" />
</div>
</form>
<script type="text/javascript">
function DeleteConfirm() {
if (confirm("Are you sure you want to delete this customer from excluded customer list ?")) {
return true;
}
return false;
}
</script>
</body>
</html>
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;
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
private DataTable _Source;
public WebForm1()
{
ResetData();
}
private void ResetData()
{
_Source = new DataTable();
_Source.Columns.Add("Name", typeof(string));
_Source.Columns.Add("Number", typeof(string));
Random rn = new Random();
for (int t = 0; t < 100; t++)
{
_Source.Rows.Add(rn.Next(1, 10).ToString(), rn.Next(1, 10).ToString());
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GridView1.DataBind();
}
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
_Source.Rows.RemoveAt(e.RowIndex);
//GridView1.DataBind();
Response.Redirect("~/WebForm1.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
ResetData();
GridView1.DataBind();
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
GridView1.DataSource = _Source;
}
protected void Button2_Click(object sender, EventArgs e)
{
var button = sender as Button;
button.Enabled = false;
var hidden = button.Parent.FindControl("HiddenField2") as HiddenField;
var name = hidden.Value;
DeletForName(name);
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
// GridView1.DataSource = _Source;
//GridView1.DataBind();
}
private void DeletForName(string name)
{
foreach (DataRow row in _Source.Rows)
if (row["Name"].Equals(name))
{
_Source.Rows.Remove(row);
break;
}
}
}
}

You basically need to store the data source between requests. One option would be to use the Session variable:
public partial class WebForm1 : System.Web.UI.Page
{
private DataTable _Source;
public WebForm1()
{
}
private void ResetData()
{
_Source = new DataTable();
_Source.Columns.Add("Name", typeof(string));
_Source.Columns.Add("Number", typeof(string));
Random rn = new Random();
for (int t = 0; t < 100; t++)
{
_Source.Rows.Add(rn.Next(1, 10).ToString(), rn.Next(1, 10).ToString());
}
Session["data"] = _Source;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ResetData();
GridView1.DataBind();
}
_Source = Session["data"] as DataTable;
}
protected void GridView1_RowDeleted(object sender, GridViewDeletedEventArgs e)
{
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
((DataTable)Session["data"]).Rows.RemoveAt(e.RowIndex);
}
protected void Button1_Click(object sender, EventArgs e)
{
ResetData();
GridView1.DataBind();
}
protected void GridView1_DataBinding(object sender, EventArgs e)
{
GridView1.DataSource = _Source;
}
protected void Button2_Click(object sender, EventArgs e)
{
var button = sender as Button;
button.Enabled = false;
var hidden = button.Parent.FindControl("HiddenField2") as HiddenField;
var name = hidden.Value;
DeletForName(name);
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
}
private void DeletForName(string name)
{
foreach (DataRow row in _Source.Rows)
if (row["Name"].Equals(name))
{
_Source.Rows.Remove(row);
break;
}
}
}
Basically when the page loads, if it is not a post back, it creates a new DataTable and stores it in the Session variable. If it is a post back, it pulls the already existing data from the Session variable. Also, you only want to call your ResetData function when you need to create a new DataTable, so I took it out of the constructor.
Also, be sure the Name column of your actual data source is unique, because your delete function will delete the first row that has the name you are looking for, not necessarily the row you selected for deletion.
Hope this helps!
EDIT
Two possibilities. I think the most likely is that you want to keep the deleted data in the table, but just mark it as deleted and disable its delete button in the gridview. To do this, my instinct is to add a boolean column to the table that indicates whether a row has been deleted or not. Then when a row is databound, check if it has been deleted and the disable the button accordingly:
private void DeletForName(string name)
{
foreach (DataRow row in _Source.Rows)
if (row["Name"].Equals(name))
{
row["Deleted"] = true;
break;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((bool)((System.Data.DataRowView)e.Row.DataItem)["Deleted"])
{
((Button)e.Row.FindControl("Button2")).Enabled = false;
}
}
}
If you want to remove the item from the table but still disable the button at the index of the rows you have deleted, that would be a little more complicated. Let me know if that's the case and I can try to help with that, but it seems more likely the above is what you want.

Related

Dynamically created Dropdownlist inside Gridview doesnot fire event on second time

I have been developing a webpage which uses n number of dropdownlists which are binding dynamically inside a gridview. I want to perform operations based on the dropdownlist's selectedindexchanged event. I had done that and working good, but when I changed dropdownlist on second time It does postback but not calls the event.
You can see my code here
<%# Page Language="C#" AutoEventWireup="true" CodeFile="gridDropDownTest.aspx.cs"
Inherits="gridDropDownTest" %><!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></title></head><body> <form id="form1" runat="server"> <div> <asp:GridView ID="gridLedgeDetails" runat="server" OnRowDataBound="OnRowDataBound"
OnDataBound="gridLedgeDetails_DataBound"> </asp:GridView>
</div>
</form></body></html>
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
public partial class gridDropDownTest : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
databind();
}
public void databind()
{
DataTable dt = new DataTable();
dt.Columns.Add("Mode");
dt.Rows.Add("");
dt.Rows.Add("");
gridLedgeDetails.DataSource = dt;
gridLedgeDetails.DataBind();
}
protected void OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
DropDownList ddlMode = new DropDownList();
ddlMode.Width = 90;
ddlMode.Attributes.Add("style", "background-color:#ff6600;");
ddlMode.Items.Add("Regular");
ddlMode.Items.Add("Monthwise");
ddlMode.SelectedIndexChanged += new EventHandler(ddlMode_Indexchanged);
ddlMode.AutoPostBack = true;
ddlMode.ID = "ddlMode_";
e.Row.Cells[0].Controls.Add(ddlMode);
}
}
protected void gridLedgeDetails_DataBound(object sender, EventArgs e) { }
protected void ddlMode_Indexchanged(object sender, EventArgs e)
{
string uid = this.Page.Request.Params.Get("__EVENTTARGET");
if (uid != null && uid.Contains("ddlMode_"))
{
string[] values = uid.Split('$');
string row = values[1].Replace("ctl", "");
Control ctrl = Page.FindControl(uid);
DropDownList ddl = (DropDownList)ctrl;
if (ddl.SelectedIndex == 1)
{
}
}
}
}
enter image description here
For this you need to take and bind the dropdownlist again in Page_PreInit page method.
For Example....
protected void Page_PreInit(object sender, EventArgs e)
{
// here you need to build the gridview again.
// then the state will retain same......
}

How to retain gridview data when postback?

I have fill data in grid view. And also i have written in code inside Row Data Bound for changing image URL to image.
Here is the code:
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
if(cellValue.StartsWith("http:"))
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = e.Row.Cells[i].Text.Trim();
HyperLink hb = new HyperLink();
hb.Controls.Add(img);
e.Row.Cells[i].Controls.Add(hb);
}
}
}
It is working fine. The page has another two drop down controls. If i select one drop down control, i made post back. At that time, the image inside i already wrote is changed to URL instead of Image.
Can you any one assist me to handle?
Thanks in advance.
Here is my code for the issues(i am not able to post entire code)
aspx code:
<html>
<body>
<form id="form1" runat="server">
<asp:DropDownList ID="DropDownList2" CssClass="borderradius" runat="server" Height="20px" Width="190px" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged" Font-Size="11px">
</asp:DropDownList>
<asp:Button id="sidesbmt" runat="server" onclick="sidesbmt_click"/>
<asp:GridView ID="GridView1" runat="server" Width="100%" CssClass="mGrid" PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnRowDataBound="GridView1_RowDataBound" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
BorderStyle="None" GridLines="Both">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
</asp:GridView>
</body>
</html>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
}
protected void sidesbmt_Click(object sender, EventArgs e)
{
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
if(cellValue.StartsWith("http:"))
{
System.Web.UI.WebControls.Image img = new System.Web.UI.WebControls.Image();
img.ImageUrl = e.Row.Cells[i].Text.Trim();
HyperLink hb = new HyperLink();
hb.Controls.Add(img);
e.Row.Cells[i].Controls.Add(hb);
}
}
}
This problem happens when you add controls dynamically and this control does not exist during the Page Init event. To restore the viewstate to the control after postback, the control has to be present in the control tree.
You can try changing your code a bit like this.
Conver the column which displays the image and url into template field
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="literalUrl" Text='<%#Eval("The fieldname")%>'></asp:Literal>
<asp:Image runat="server" ID="imageUrl" Visible="false" />
</ItemTemplate>
</asp:TemplateField>
Then in the rowdatabound event toggle the view of image and literal
protected void GridView1_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
for (int i = 1; i < e.Row.Cells.Count; i++)
{
string cellValue = e.Row.Cells[i].Text.Trim();
Literal literal = e.Row.Cells[i].FindControl("literalUrl") as Literal;
Image imageUrl = e.Row.Cells[i].FindControl("imageUrl") as Image;
if (literal != null && imageUrl != null)
{
if (literal.Text.StartsWith("http:"))
{
imageUrl.ImageUrl = literal.Text.Trim();
imageUrl.Viisible = true;
literal.Visible = false;
}
}
}
}

How to temporarily store DataTable after Binding

I have two GridViews in which I populate Data on PageStart from database. When I refresh the page (on Post Back), I could not see the datatable content. so I thought of Databinding the GridView again on every pageload. In order to bind the Data I need to store the Data somewhere temporarily. Which one is the Best method to store data temporarily?
In my First Grid there are about 10 rows and in the Second GridView I have about 200 rows. and I'm not using Paging
Here's a fully working sample using ViewState but you can change it for other caching methods.
Default.aspx
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView runat="server" ID="gvProd" AutoGenerateColumns="false" OnRowDataBound="gvProd_RowDataBound" OnRowCommand="gvProd_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Product">
<ItemTemplate>
<asp:Literal runat="server" ID="litNm"></asp:Literal>
<asp:DropDownList runat="server" ID="ddlQty"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Add To Cart">
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbnAdd" Text="Add To Cart" CommandName="AddToCart"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<hr />
<asp:GridView runat="server" ID="gvCart" AutoGenerateColumns="false" OnRowDataBound="gvCart_RowDataBound" OnRowCommand="gvCart_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="litNm"></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQty"></asp:TextBox>
<asp:Button runat="server" ID="btnUpdate" Text="Update Qty" CommandName="UpdateCart" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication1
{
public partial class Default : System.Web.UI.Page
{
[Serializable]
public class Product
{
public int PID { get; set; }
public string Name { get; set; }
public Product(int i) { this.PID = i; this.Name = "product " + i.ToString(); }
}
[Serializable]
public class CartItem
{
public Product Prod { get; set; }
public int Qty { get; set; }
public CartItem(Product p, int q) { this.Prod = p; this.Qty = q; }
}
public List<CartItem> myCart = new List<CartItem>();
public List<CartItem> MyCart
{
get
{
if (ViewState["cart"] == null)
{
ViewState["cart"] = new List<CartItem>();
}
return ViewState["cart"] as List<CartItem>;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
BindProdGrid();
}
protected void BindProdGrid()
{
gvProd.DataSource = GetProducts();
gvProd.DataBind();
}
protected List<Product> GetProducts()
{
var ret = new List<Product>();
ret.Add(new Product(1));
ret.Add(new Product(2));
return ret;
}
protected void gvProd_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
var row = (e.CommandSource as LinkButton).NamingContainer as GridViewRow;
var ddl = row.FindControl("ddlQty") as DropDownList;
var qty = Convert.ToInt32(ddl.SelectedValue);
var pid = Convert.ToInt32(e.CommandArgument);
AddToCart(pid, qty, increase: true);
BindCartGrid(this.MyCart);
}
}
protected void AddToCart(int pid, int qty, bool increase = false)
{
var cartItem = this.MyCart.Find(o => o.Prod.PID == pid);
if (cartItem == null)
this.MyCart.Add(new CartItem(new Product(pid), qty));
else
if (increase)
cartItem.Qty += qty;
else
cartItem.Qty = qty;
}
protected void gvProd_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as Product;
var litNm = e.Row.FindControl("litNm") as Literal;
litNm.Text = item.Name;
var ddlQty = e.Row.FindControl("ddlQty") as DropDownList;
ddlQty.Items.Add(new ListItem("1", "1"));
ddlQty.Items.Add(new ListItem("10", "10"));
var lbnAdd = e.Row.FindControl("lbnAdd") as LinkButton;
lbnAdd.CommandArgument = item.PID.ToString();
}
}
protected void BindCartGrid(List<CartItem> items)
{
gvCart.DataSource = items;
gvCart.DataBind();
}
protected void gvCart_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var item = e.Row.DataItem as CartItem;
var litNm = e.Row.FindControl("litNm") as Literal;
litNm.Text = item.Prod.Name + " (pid:" + item.Prod.PID.ToString() + ")";
var txtQty = e.Row.FindControl("txtQty") as TextBox;
txtQty.Text = item.Qty.ToString();
txtQty.Attributes["data-pid"] = item.Prod.PID.ToString();
}
}
protected void gvCart_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "UpdateCart")
{
var row = (e.CommandSource as Button).NamingContainer as GridViewRow;
var txtQty = row.FindControl("txtQty") as TextBox;
var qty = Convert.ToInt32(txtQty.Text);
var pid = Convert.ToInt32(txtQty.Attributes["data-pid"]);
AddToCart(pid, qty, increase: false);
BindCartGrid(this.MyCart);
}
}
}
}
Usage of Cache object vs Session again will depend upon whether you want the data to be stored temporarily per session or for all the sessions you want to store the same data.
Session can be used if you want the same data to be maintained only for a particular session of your application.
Cache can be used for all the user sessions across your application.
The best place to store the data will be sessions. Viewstate will bring all the data on client side which is an undesirable network/bandwidth overhead.
your PageStart should look like this:
public void PageStart()
{
if(Session["dt"] == null || !(Session["dt"] is datatable)){
datatable dt;
///your dt populating code
Session["dt"] = dt;
}
yourGridView.datasource = (datatable)Session["dt"];
yourGridView.databind();
}
To address data persistence between postbacks you have several options. I am really against ViewState except in very specific cases where you have a very little amount of data (that's where Microsoft fail in WebForms - its default behaviour is DemoWare).
I would suggest keeping your data in a Cache object and upon postback, read it from that object. But it really depends on your specific use case. There are different techniques.
This is all what you need to do.
Place you method or function which fills the gridview with data like this.
private void FillGrid()
{
DataTable dt = new DataTable();
dt = //Fill you datatable
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
This is what you gotta do on pageload event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.FillGrid();
}
}

Lost Component After choice SelectIndexChanged at GridView

When I choice row at GridView of UserControl.This gridview disappear.
Main page (aspx page)
1.1.Html
<body>
<form id="form1" runat="server">
<div>
<asp:PlaceHolder ID="plh" runat="server"></asp:PlaceHolder>
</div>
</form>
</body>
1.2.CodeBehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Test2.Admin.WebUserControl1[] wuc = new Test2.Admin.WebUserControl1[2];
for (int i = 0; i < 2; i++)
{
plh.Controls.Add(new LiteralControl("<div id='dvChannel' runat='server' style='width: 200px;float:left;padding-left:20px;'>"));
wuc[i] = (Test2.Admin.WebUserControl1)LoadControl("WebUserControl1.ascx");
wuc[i].ID = "wuc" + i.ToString();
plh.Controls.Add(wuc[i]);
plh.Controls.Add(new LiteralControl("</div>"));
}
}
}
UserControl
2.1.html
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="Test2.Admin.WebUserControl1" %>
<asp:GridView ID="GridView1" runat="server" AutoGenerateSelectButton="true"
OnSelectedIndexChanged="gvSelected">
</asp:GridView>
2.2.Codebehind
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var list = (new[] {
new { Price = 30 } ,
new { Price = 30 },
new { Price = 30 },
new { Price = 30 }
});
GridView1.DataSource = list;
GridView1.DataBind();
}
}
protected void gvSelected(object sender,EventArgs e)
{
GridViewRow row = GridView1.Rows[GridView1.SelectedIndex];
row.BackColor = Color.Red;//Set red color for this row on gridview
}
When I choice row at GridView of UserControl.This gridview disappear.
What should I do for getting it work correct.
Do you have any solution?
You need to Load the GridView even in Postbacks.
Try removing the condition - if (!Page.IsPostBack)
Or, write a different code snippet in else block - for setting the datasource & binding the Grid.

Why all the page in the GridView show the same data as that in the first page?

I use a GridView to show data from an excel file, after setting the GridView's Allowpage to true. All the pages show the same content as that in the first page. Thanks to anyone who tell me why!
The HTML code of the GrdiView is:
<asp:GridView ID="GridView_NewStaff" runat="server" AutoGenerateColumns="False"
CellPadding="4" Font-Size="Small" ForeColor="#333333" AllowPaging="True"
AllowSorting="True" onpageindexchanging="GridView_NewStaff_PageIndexChanging"
PageSize="20">
<pagersettings firstpagetext="First" lastpagetext="Last">
Mode="NextPreviousFirstLast" NextPageText="Next" PageButtonCount="4"
PreviousPageText="Previous" />
<columns>......
The C# code is:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridView();
}
}
protected void Button_ReadFile_Click(object sender, EventArgs e)
{
bindGridView();
}
public void bindGridView()
{
if (FileUpload_StaffInfo.HasFile)
{
string InfoFile_Name = Server.MapPath(InfoFileDirectory) + FileUpload_StaffInfo.FileName;
FileUpload_StaffInfo.SaveAs(InfoFile_Name);
dataTable_Excel = new DataTable();
if (InfoFile_Name.EndsWith(".xlsx"))//Read Excel2007-2010 format file
{
StaffExcelXML StaffNewXML = new StaffExcelXML();
StaffNewXML.ExcelInput(InfoFile_Name, ref dataTable_Excel)
}
else if (InfoFile_Name.EndsWith(".xls"))//Read Excel1997-2003 format file
{
StaffXLS StaffNewXLS = new StaffXLS();
StaffNewXLS.ExcelInput(InfoFile_Name, ref dataTable_Excel);
}
GridView_NewStaff.DataSource = dataTable_Excel;
GridView_NewStaff.DataBind();
}
}
protected void GridView_NewStaff_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView_NewStaff.PageIndex = e.NewPageIndex;
bindGridView();
}
change
GridView_NewStaff.PageIndex = e.NewPageIndex;
bindGridView();
to
GridView_NewStaff.PageIndex = e.NewPageIndex;
GridView_NewStaff.DataBind();
After assigning a new Page index to the GridView, just rebind the GridView control.

Categories

Resources