Custom Page numbers for Gridview paging with desired pager style - c#

I am implementing a functionality display records in gridview not as per default page numbers but as per the department numbers. e.g.
I have 20 departments within that there are students so I want to show department Identifier i.e. D1,D2,D3... as a page numbers and clicking on that students in that department would be loaded in grid.
I want paging like the attached image, on clicking "..." in page numbers it should take me to next set of page numbers.
How should I go for implementation of such a paging for asp.net gridview?

It will be paging through the records using the “Next” and the “Previous” buttons. The Label control will display our current location in the paged GridView. Let’s first set up some of the variables.
protected int currentPageNumber = 1;
private const int PAGE_SIZE = 10;
The currentPageNumber represents the current page of the GridView, and the PAGE_SIZE is the total number of records displayed on each page. You can also allow the user to adjust the page size using a DropDownList, but that is not covered in this article.
Next, we need to bind the data source to the GridView. Let’s check out the BindData method as a whole, and later I will dissect it so you will have a better idea.
private void BindData()
{
string connectionString = "Server=localhost;" +
"Database=Northwind;Trusted_Connection=true";
SqlConnection myConnection = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand("usp_GetProducts",
myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#startRowIndex",
currentPageNumber);
myCommand.Parameters.AddWithValue("#maximumRows", PAGE_SIZE);
myCommand.Parameters.Add("#totalRows", SqlDbType.Int, 4);
myCommand.Parameters["#totalRows"].Direction =
ParameterDirection.Output;
SqlDataAdapter ad = new SqlDataAdapter(myCommand);
DataSet ds = new DataSet();
ad.Fill(ds);
gvProducts.DataSource = ds;
gvProducts.DataBind();
// get the total rows
double totalRows = (int)myCommand.Parameters["#totalRows"].Value;
lblTotalPages.Text = CalculateTotalPages(totalRows).ToString();
lblCurrentPage.Text = currentPageNumber.ToString();
if (currentPageNumber == 1)
{
Btn_Previous.Enabled = false;
if (Int32.Parse(lblTotalPages.Text) > 0)
{
Btn_Next.Enabled = true;
}
else
Btn_Next.Enabled = false;
}
else
{
Btn_Previous.Enabled = true;
if (currentPageNumber == Int32.Parse(lblTotalPages.Text))
Btn_Next.Enabled = false;
else Btn_Next.Enabled = true;
}
}
Now, let’s take a look at the above code in more detail. I am sending the currentPageNumber and the PAGE_SIZE into the database so I can get the data for the current page. The totalRows variable returns the total number of rows in the table. Once I have totalRows, I calculate the total number of pages that will be used for this GridView. The total number of pages is calculated by using a small helper function:
private int CalculateTotalPages(double totalRows)
{
int totalPages = (int) Math.Ceiling(totalRows / PAGE_SIZE);
return totalPages;
}
At the end of the BindData method, there are some conditional checks which ensure that the Next and Previous buttons are only displayed when applicable.
Attaching the Events to the Buttons
The final thing that is left is to attach the events to the Button controls. Check out the following code in which I created two Button controls.
<asp:Button ID="Btn_Previous" CommandName="Previous"
runat="server" OnCommand="ChangePage"
Text="Previous" />
<asp:Button ID="Btn_Next" runat="server" CommandName="Next"
OnCommand="ChangePage" Text="Next" />
Both the buttons call the ChangePage event which is shown below:
// This method will handle the navigation/ paging index
protected void ChangePage(object sender, CommandEventArgs e)
{
switch (e.CommandName)
{
case "Previous":
currentPageNumber = Int32.Parse(lblCurrentPage.Text) - 1;
break;
case "Next":
currentPageNumber = Int32.Parse(lblCurrentPage.Text) + 1;
break;
}
BindData();
}
The ChangePage event is used to change the page number of the GridView and also to update the Label text by calling the BindData method.
Source

Related

Keeping ViewState of page after PostBack Refresh

I have a drop down list with the list items created in the code behind. ddlFill(). Pretty simple and does the job. It's populated with the current month and some months ahead. I use this drop down as a selection to fill a Gridview. When this drop down index changes, it changes a hidden field value and a corresponding query to fill the gridview. All this works as it should. Within the gridview I have another dropdown list and a button. Both submit the selected row to a database. That also works fine. The problem is, each time one of these rows submits to the database, it causes a post back and it resets the whole page. It resets the drop down list to the first list item . I.E. I change the drop down list to index 4 for example. Which would be April in this case. If I submit a row to the db, the page refreshes and goes back to index 0 .. January in this case. How do I keep it from resetting this way and maintaining the position I was in when I submitted the row?
I have tried a few different options. I've tried session states. hidden field value changes. Nothing seems to work. It either does not perform the post back therefore never submits to the db or it does the post back, submits correctly, then resets the whole page. Including resetting the hiddenfield value back to 0
/* This is up in Page load. */
if (Session["pageStatus"] != null)
{
if (Session["pageStatus"].ToString() == "Loaded")
{
hf2.Value = "Loaded";
}
}
else
{
hf2.Value = "New";
}
if (Session["selectedMonth"] != null)
{
hf1.Value = Session["selectedMonth"].ToString();
}
if (ViewState["button_was_clicked"] != null)
{
ddlFill();
StyleDDL();
}
lblTestlabel.Text = hf2.Value;
AddAttributes();
ShowMonth();
if (!Page.IsPostBack)
{
btnReviewCurrentMonth_OnClick(sender, e);
ddlFill();
StyleDDL();
}
private void ddlFill()
{
string a, b, c, d, e, f;
a = "0";
b = "1";
c = "2";
d = "3";
e = "4";
f = "5";
DropDownList1.Items.Insert(0, new ListItem(ReturnMonth(a))); // A blank object call and the ReturnMonth Method fill the list items.
DropDownList1.Items.Insert(1, new ListItem(ReturnMonth(b)));
DropDownList1.Items.Insert(2, new ListItem(ReturnMonth(c)));
DropDownList1.Items.Insert(3, new ListItem(ReturnMonth(d)));
DropDownList1.Items.Insert(4, new ListItem(ReturnMonth(e)));
DropDownList1.Items.Insert(5, new ListItem(ReturnMonth(f)));
/* These were for various testing options to get it to maintain the
state */
hf2.Value = "Loaded";
Session["pageStatus"] = "Loaded";
DropDownList1.SelectedIndex = Int32.Parse(hf1.Value);
}
My goal is to maintain the state of the page after the submission to the db occurs.
I found this question difficult to ask because it had so many moving parts. The ddlFill() method wasn't the problem. All it litterally did was fill list items. Those corresponding Selected Index values would change when selected and based on those values I would assign a different value to a hidden field. Which was then used as SqlDataSource control variable and would bring back GridView data based on that control value.
A drop down list within the gridview was used to select and submit the indexed row to a SQL DB. At the end of that code I was refreshing the page. It needed a refresh to properly submit and bring back a fresh Gridview with the previously submitted row now gone. That was the problem. When it refreshed, it changed the hidden field value to 0 and reset everything back. So, here is what I did.
//This method controls the Drop Down List change event. Underwriter change.
protected void DropDownList1_OnSelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
int idx = row.RowIndex;
GridView1.SelectedIndex = idx;
string Client = GridView1.SelectedRow.Cells[0].Text;//Client Name
string NewUw = ddl.Text.ToString();
int UniqCNT = new Int32();
UniqCNT = Int32.Parse(GridView1.SelectedRow.Cells[1].Text.ToString()); //UniqClient */
string ExpPolicyNums = GridView1.SelectedRow.Cells[2].Text;
int Ub = Int32.Parse(GridView1.SelectedRow.Cells[10].Text);//UniqBroker
DateTime ExperationDate = DateTime.Parse(GridView1.SelectedRow.Cells[6].Text); //ExpDate
string Company = GridView1.SelectedRow.Cells[7].Text; //Company issuer
string Broker = GridView1.SelectedRow.Cells[8].Text; //Broker_Name
string Premium = GridView1.SelectedRow.Cells[3].Text; //Premiums
string TotalPremium = GridView1.SelectedRow.Cells[4].Text; //Total premiums
string Reviewed = "No"; //Updates the DB and shows that it hasn't been reviewed by the Message Creator
//DateCreated gets inserted when record is created
string InsertedBy = Request.LogonUserIdentity.Name.Substring(Request.LogonUserIdentity.Name.LastIndexOf(#"\") + 1);
DateTime dateUpDated = DateTime.Now; //Inserts a dateUpdated record
string query = "INSERT INTO [GTU_Apps].[dbo].[Reviewed_Renewal_Policy] (UniqClient, Client, [Expiring_Policies], Premiums, TotalPremium, UniqBroker, ExpDate, NewUw, Company, Broker_Name, Reviewed, DateUpDated, InsertedBy) " +
"VALUES (#UniqCNT, #Client, #ExpPolicyNums, #Premium, #TotalPremium, #Ub, #ExperationDate, #NewUw, #Company, #Broker, #Reviewed, #dateUpDated, #InsertedBy)";
using (SqlConnection conn = new SqlConnection("Data Source=GTU-BDE01;Initial Catalog=GTU_Apps;Integrated Security=True"))
{
using (SqlCommand comm = new SqlCommand(query, conn))
{
comm.Parameters.AddWithValue("#UniqCNT", UniqCNT);
comm.Parameters.AddWithValue("#Client", Client);
comm.Parameters.AddWithValue("#ExpPolicyNums", ExpPolicyNums);
comm.Parameters.AddWithValue("#Premium", Premium);
comm.Parameters.AddWithValue("#TotalPremium", TotalPremium);
comm.Parameters.AddWithValue("#Ub", Ub);
comm.Parameters.AddWithValue("#ExperationDate", ExperationDate);
comm.Parameters.AddWithValue("#NewUw", NewUw);
comm.Parameters.AddWithValue("#Company", Company);
comm.Parameters.AddWithValue("#Broker", Broker);
comm.Parameters.AddWithValue("#Reviewed", Reviewed);
comm.Parameters.AddWithValue("#dateUpDated", dateUpDated);
comm.Parameters.AddWithValue("#InsertedBy", InsertedBy);
conn.Open();
comm.ExecuteNonQuery();
conn.Close();
}
}
GridView1.DataBind();
GridView1.SelectedIndex = -1;
int index = DropDownList1.SelectedIndex;
ConfirmIndex(index);
//End(sender, e);
}
Using the DataBind worked. It only refreshed the Gridview. Which was really what I needed. I had other items that were refreshing too. That's why those calls below it are there. If someone sees this, hopefully it will help.

How to select a row in a DataGridView programmatically AND trigger DataGridView.SelectionChanged event?

For the life of me I cannot seem to figure this out. I have a long DataGridView (that does not allow MultiSelect) and when a user commits a change to the data, the data from the grid is purged and redrawn (because changes can affect multiple rows, this was the simpler approach). However, when I try to select the row programmatically, it does not also fire the DataGridView.SelectionChanged event, which I use to display data from an array which is correlated to the DataGridView current cell index. When doMagicStuff executes, the values for the wrong index (specifically, index 0) is show.
private void doMagicStuff()
{
int selRow = myDGV.CurrentCell.RowIndex;
myDGV.Rows.Clear();
/*Perform Task, Redraw data*/
myDGV.CurrentCell = myDGV[selRow, 0];
}
private void myDGV_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = myDisplayValue1[myDGV.CurrentCell.RowIndex];
Label2.Text = myDisplayValue2[myDGV.CurrentCell.RowIndex];
TextBox1.Text = myEditValue1[myDGV.CurrentCell.RowIndex];
TextBox2.Text = myEditValue2[myDGV.CurrentCell.RowIndex];
}
Make sure that your client settings and OnSelectedIndexChanged is set like so: (ASP.NET AJAX)
.aspx page
<telerik:RadGrid ID="Grid1" runat="server" OnSelectedIndexChanged="Grid1_SelectedIndexChanged" OnItemDataBound="Grid1_ItemDataBound" OnPreRender="Grid1_PreRender">
<ClientSettings EnablePostBackOnRowClick="true">
<Selecting AllowRowSelect="true"></Selecting>
</ClientSettings>
</telerik:RadGrid>
aspx.cs page
protected void Grid1_SelectedIndexChanged(object sender, EventArgs e)
{
string value = null;
foreach(GridDataItem item in Grid1.SelectedItems)
{
//column name is in doub quotes
value = item["Name"].Text;
}
}
Add a button click to the form to test the selected values in the DataGridView.. double click that button then paste this code in there
foreach (DataGridViewRow row in myDGV.SelectedRows)
{
Label1.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
Label2.Text = //This should be hard coded the only thing that should change dynamically is the TextBox Values
TextBox1.Text = row.Cells[0].Value.ToString();//change the 0 or 1 to fit your column Index position
TextBox2.Text = row.Cells[2].Value.ToString();
}
also if you have 4 columns and 4 text boxes then you will assign all of the textbox.Text values within the foreach loop just follow the pattern and increase the index by 1 so 2 textboxes means row.Cells[0] is the first column row.Cells[1] is the second column ...etc

Display gridview row count based on dropdown selection

I am using this code to take a gridview count and display in a label on page load and works fine.
Page Load:
int rowCount = dtDetails.Rows.Count;
lblTotalRows.Text = rowCount.ToString() + "records found";
I have a dropdown above my gridview and when I select dropdown values the row count have to changed based on the dropdown selected values.
How could I possibly do that in dropdown selected index change
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtGroup = DataRepository.GetGroup(ddlGroup.Text);
gvDetails.DataSource = dtGroup;
gvDetails.DataBind();
//Now how could I possible show the respective row counts in the label
}
protected void ddlGroup_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dtDept = DataRepository.GetDept(ddlGroup.Text, ddlDept.Text);
gvDetails.DataSource = dtDept;
gvDetails.DataBind();
//Now how could I possible show the respective row counts of both group and
dept row count since they are cascading dropdowns in the label
}
Any suggestions?
I tend to make a SetData() method so all this kind of code is in one place. So in this instance I would:
protected void SetData(DataTable dtGroup)
{
// Bind the data to the grid
gvDetails.DataSource = dtGroup;
gvODetails.DataBind();
// Show row count
if (!dtGroup.Rows.Count.Equals(0))
lblTotalRows.Text = dtGroup.Rows.Count + " records found";
else
lblTotalRows.Text = "No records found";
}
This way you only have one place that does all the 'bindind' so in your Page_Load you can just call this SetData() method and pass in the datatable, and the same on your SelectedIndexChanged.

How to next page number in gridview every 1 minute with code behind

I try to refresh page with timer every 1 minute and display data in gridview on next page until last record.
What should I do?
protect void Timer1_Tick(object sender, EventArgs e)
{
if(GridView1.PageIndex==GridView.PageCount)
{
GridView1.PageIndex=1;
}
else
{ int pageno = GridView1.PageIndex+1;
GridView1.PageIndex=pageno;
}
GridView1.DataBind(); Timer1.Interval=600000;
}
PageIndex is zero-based index and PageCount is calculated by dividing the total number of records in the data source by the number of records displayed in a page (as specified by the PageSize property) and rounding up.
so PageIndex will never equal to PageCount
if(GridView1.PageIndex == (GridView1.PageCount -1))
{
GridView1.PageIndex = 0;
}
else
{
GridView1.PageIndex = GridView1.PageIndex + 1;
}
GridView1.DataBind();
You can use Ajax Update panel and put your grid inside the panel. Then you can use above code inside theOnTick event of Timer which set as AsyncPostBackTrigger, check below SO question for example
Timer in UpdatePanel

Modal popup extender losing ID

Edit:
Added onload method:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["usersName"] != null)
{
object a = Session["_id"];
IDMaster = Convert.ToInt32(a);
GridView1.Columns[10].Visible = true;
GridView1.Columns[11].Visible = true;
}
I'm using a modal pop up extender to warn my customers that the item amount of a specific item is over a certain amount.
I have two buttons within this extender that allows a user to confirm they want an email sending to them when new stock arrives or not.
The trigger for the 'yes' button works perfectly but when i send the row ID to the constructor of my class used to store the email details it is always set to 0, even though the variable is global.
Here is my code to explain the issue further:
Button within my modal to add items to the cart:
protected void LinkButton1_Click(object sender, EventArgs e)
{
GridViewRow row = ((Button)sender).Parent.Parent as GridViewRow;
TextBox t = (TextBox)row.FindControl("txtQuan");
*********Gain the item row ID (this is what needs to be passed*******
object ID = GridView1.DataKeys[row.RowIndex].Value;
*********This ID should be passed but is setting to 0************
rowID = Convert.ToInt32(ID);
string qty = t.Text;
int stockToAdd = Convert.ToInt32(qty);
DBHandler add = new DBHandler(rowID);
int qtyCheck = add.getStockQty();
if (stockToAdd > qtyCheck)
{
Button2_ModalPopupExtender.Show();
}
else{
SqlConnection con;
con = add.openDB();
con.Open();
DBHandler idCheck = new DBHandler(rowID);
int rows = idCheck.checkCartRows();
if (rows > 0)
{
int qtyNow = idCheck.getCartQty();
int updateStock = qtyNow + stockToAdd;
idCheck.updateQty(rowID, updateStock);
updatePanel();
}
else
{
idCheck.insertCart(qty);
updatePanel();
}
add.close();
}
}
The following code shows my confirm onclick button method. Note the ID 'rowID' that was stored in the above method when the add to cart button was clicked. This rowID is is setting to 0 instead of holding the rowID value.
protected void btnOK_Click(object sender, EventArgs e)
{
***** rowID is setting to 0*******
DBoutOfStockEmail insertNewEmailDetail = new DBoutOfStockEmail(IDMaster, rowID);
DBMembershipHandler getEmail = new DBMembershipHandler(IDMaster);
string emailToSend = getEmail.emailOfMember();
insertNewEmailDetail.insertDetails(emailToSend);
}
To summaries this question: Why is the rowID variable setting to '0' when i click the yes button with the modal pop up extender?
Based on my initial Comment I am going to post this as an answer
This can be from several things.. are you checking or doing IsPostBack checks, are you holding the Value(s) in a Session Variable..? ViewState is it enabled or disabled..? can you show what your Page_Load Event Looks like

Categories

Resources