Implement Pagination in ASP.Net Gridview Control - c#

I have a gridview that is bound on page load and I've implemented insert using the footer row technique.
Now I tried the pagination in the same gridview.
I don't have errors but when changing page in the DDL of footer row I find all values duplicates.
In first page the output in DDL is:
MSG
PAY
BUY
LIS
If changed the page the second output in page number two is:
MSG
PAY
BUY
LIS
MSG
PAY
BUY
LIS
I'd greatly appreciate any suggestions.
Thanks!
I used this lines in RowDataBound:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && GridView1.EditIndex == e.Row.RowIndex)
{
DropDownList Area_DDL = (DropDownList)e.Row.FindControl("Area_DDL");
Area_DDL.DataTextField = "area_name";
Area_DDL.DataValueField = "area";
Area_DDL.DataSource = Area();
Area_DDL.DataBind();
Area_DDL.Items.FindByValue((e.Row.FindControl("Area") as Label).Text).Selected = true;
}
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList Area_DDL = (DropDownList)e.Row.FindControl("Area_DDL");
Area_DDL.DataTextField = "area_name";
Area_DDL.DataValueField = "area";
Area_DDL.DataSource = Area();
Area_DDL.DataBind();
}
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
lblPageCount.Text = GridView1.PageCount.ToString();
for (int i = 1; i <= GridView1.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = GridView1.PageIndex;
if (GridView1.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (GridView1.PageIndex + 1 == GridView1.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}

Change your code like this, I hope it help:
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridViewBind();
}
protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
{
GridViewRow gvrPager = GridView1.BottomPagerRow;
DropDownList ddlPages = (DropDownList)gvrPager.Cells[0].FindControl("ddlPages");
GridView1.PageIndex = ddlPages.SelectedIndex;
GridViewBind();
}
protected void Paginate(object sender, CommandEventArgs e)
{
int intCurIndex = GridView1.PageIndex;
switch (e.CommandArgument.ToString().ToLower())
{
case "First":
GridView1.PageIndex = 0;
break;
case "Prev":
GridView1.PageIndex = intCurIndex - 1;
break;
case "Next":
GridView1.PageIndex = intCurIndex + 1;
break;
case "Last":
GridView1.PageIndex = GridView1.PageCount - 1;
break;
}
GridView1.DataBind();
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
DropDownList ddl = (DropDownList)(e.Row.FindControl("ddlpages"));
Label lblPageCount = (Label)e.Row.FindControl("lblPageCount");
if (lblPageCount != null)
{
lblPageCount.Text = GridView1.PageCount.ToString();
for (int i = 1; i <= GridView1.PageCount; i++)
{
ddl.Items.Add(i.ToString());
}
ddl.SelectedIndex = GridView1.PageIndex;
if (GridView1.PageIndex == 0)
{
((ImageButton)e.Row.FindControl("ImageButton1")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton2")).Visible = false;
}
if (GridView1.PageIndex + 1 == GridView1.PageCount)
{
((ImageButton)e.Row.FindControl("ImageButton3")).Visible = false;
((ImageButton)e.Row.FindControl("ImageButton4")).Visible = false;
}
}
}
}

Related

How to apply "Readonly" in gridview textbox using BoundField when edit mode

I want READONLY on text box using Boundsfield. So far enabled is working but it not carry value in rowupdating
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
var nopoject = ddlproject.SelectedValue.ToString();
Int32 curntMonth = Convert.ToInt32(DateTime.Now.ToString("MM"));
int Mont1 = curntMonth - 1;
var Comtext = "Rst" + Mont1.ToString();
GridView1.EditIndex = e.NewEditIndex;
BindData();
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < GridView1.Columns.Count; i++)
{
String headertext = GridView1.Columns[i].HeaderText;
String cellText = row.Cells[i].Text;
if (Comtext == "Rst1")
{
GridView1.Rows[e.NewEditIndex].Cells[i].Enabled = true;
}}}
Below code not working :
GridView1.Rows[e.NewEditIndex].Cells[i].Attributes.Add("readonly", "readonly");
GridView1.Rows[e.NewEditIndex].Cells[i].CssClass = "read-only";
Please advise. I want readonly on boundsfield programically when inline edit
Thank you
You can use this snippet.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((e.Row.RowState & DataControlRowState.Edit) > 0)
{
TextBox textBox = e.Row.Cells[0].Controls[0] as TextBox;
textBox.Enabled = false;
}
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowState == DataControlRowState.Edit || e.Row.RowState == DataControlRowState.Alternate)
{
//on you condition
TextBox txt = (TextBox)e.Row.FindControl("ControlID");
if(txt !=null)
{
txt.Attributes.Add("readonly", "readonly");
}
}
}
You can also make textbox readonly in row editing event as below.
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
var nopoject = ddlproject.SelectedValue.ToString();
Int32 curntMonth = Convert.ToInt32(DateTime.Now.ToString("MM"));
int Mont1 = curntMonth - 1;
var Comtext = "Rst" + Mont1.ToString();
GridView1.EditIndex = e.NewEditIndex;
BindData();
foreach (GridViewRow row in GridView1.Rows)
{
for (int i = 0; i < GridView1.Columns.Count; i++)
{
String headertext = GridView1.Columns[i].HeaderText;
String cellText = row.Cells[i].Text;
if (Comtext == "Rst1")
{
//GridView1.Rows[e.NewEditIndex].Cells[i].Enabled = true;
TextBox tx_chdets = (TextBox)GridView1.Rows[e.NewEditIndex].FindControl(“TextBox1”);
if(tx_chdets!=null)
{
tx_chdets.Readonly=true;
}
}
}
}
}

ViewState with a List of strings

I am trying to save info from a Gridview on page load to a List of Strings. I then want to take that info and email it out. I have looked online for info on this, and so far I have found nothing. I don't understand if my implementation of the ViewState is wrong or simple in the wrong place. Please help?
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
messages = (List<string>)ViewState["messages"];
}
if (Page.IsPostBack)
{
changeByVendor();
//mailFunction(messages);
}
if (!IsPostBack)
{
mailFunction(messages);
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if ((GridView1.DataSourceID == "SqlDataSource2" || GridView1.DataSourceID == "SqlDataSource1") && !(e.Row.Cells[11].Text.Equals(" ")))
{
DateTime myDate = Convert.ToDateTime(e.Row.Cells[11].Text);
if (DateTime.Now > myDate)
{
e.Row.ForeColor = System.Drawing.Color.Red;
}
DateTime myDate2 = Convert.ToDateTime(e.Row.Cells[13].Text);
if (myDate2 > DateTime.Now && myDate2 < DateTime.Now.AddDays(28))
{
e.Row.Cells[13].BackColor = System.Drawing.Color.Yellow;
string thisRow = "";
for (int i = 0; i < e.Row.Cells.Count; i++)
{
thisRow = thisRow + e.Row.Cells[i];
}
messages.Add(thisRow);
}
}
else if (GridView1.DataSourceID == "SqlDataSource4" && !(e.Row.Cells[6].Text.Equals(" ")))
{
DateTime myDate = Convert.ToDateTime(e.Row.Cells[6].Text);
if (DateTime.Now > myDate)
{
e.Row.ForeColor = System.Drawing.Color.Red;
}
DateTime myDate2 = Convert.ToDateTime(e.Row.Cells[7].Text);
if (myDate2 > DateTime.Now && myDate2 < DateTime.Now.AddDays(28))
{
e.Row.Cells[7].BackColor = System.Drawing.Color.Yellow;
}
}
ViewState["messages"] = messages;
}
}
Let's suppose we have the following example:
List<string> input = new List<string>();
protected void Page_Load(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<string> msgs = new List<string>() { "1", "2", "3" };
ViewState["messages"] = msgs;
}
This will certainly store the List of strings in the viewstate. The problem is, that when we trigger the button click event, the Page_Load event will fire BEFORE the Button1_Click event, thus, the viewstate will still be empty. This can be managed by passing the code into the Page_PreRender event, which will fire after the button_click event.
protected void Page_PreRender(object sender, EventArgs e)
{
if (ViewState["messages"] != null)
{
input = (List<string>)ViewState["messages"];
}
}

how to add and catch event of linkbutton inside the gridview by dynamically

<asp:GridView ID="grid_planningStaff" runat="server"
AutoGenerateColumns="false"
OnRowCommand="yourgridview_RowCommand"
CssClass="table_style01 table100"
BorderWidth="3px"
ForeColor="Black"
OnRowDataBound="grid_planning_RowdataBound">
protected void grid_planning_RowdataBound(object sender, GridViewRowEventArgs e)
{
//try
//{
if (e.Row.RowType != DataControlRowType.Header)
{
DataSet ds = new DataSet();
planningStaffCommon.StaffID = sid;
ds = objDALPlanningModule.GetStaffMeetingData(planningStaffCommon);
if (ds.Tables[0].Rows.Count > 0)
{
for (int J = 0; J < ds.Tables[0].Rows.Count; J++)
{
dateofcell = Convert.ToString(ds.Tables[0].Rows[J]["FromDate"]);
from = Convert.ToInt16(ds.Tables[0].Rows[J]["datea"]);
string clientids = Convert.ToString(ds.Tables[0].Rows[J]["MeetingType"]);
colorvalue = Convert.ToInt32(ds.Tables[0].Rows[J]["ColorValues"]);
//set Color
if (colorvalue == 1)
{
//DataSet dscolor = new DataSet();
//objDALPlanningModule._dtLOVDescription=clientids;
//dscolor=objDALPlanningModule.GetParaMeterDetailsDAL();
//if (dscolor.Tables[0] != null)
//{
// setcolor = Convert.ToString(dscolor.Tables[0].Rows[0]["Value"]);
//}
//else
//{
//break
//}
if (clientids == "Test Value1")
{
setcolor = "GREEN";
}
else
if (clientids == "Testy Value2")
{
setcolor = "ORANGE";
}
else
{
setcolor = "RED";
}
}
else
{
setcolor = "Aqua";
}
//color and fill clients
for (int i = from; i <= from; i++)
{
LinkButton lkBtn = new LinkButton();
lkBtn.ForeColor = Color.Black;
lkBtn.Font.Underline = false;
lkBtn.ID = "link_button" + i;
lkBtn.Text = clientids;
lkBtn.CommandName = "Edit";
//lkBtn.OnClientClick = "Edit";
//lkBtn.Click += ViewDetails;
HiddenField hdndate = new HiddenField();
hdndate.ID = "hdn" + i;
hdndate.Value = dateofcell;
e.Row.Cells[i].Controls.Add(hdndate);
e.Row.Cells[i].BackColor = Color.FromName(setcolor);
e.Row.Cells[i].Controls.Add(lkBtn);
}
}
}
//hide other extra created rows
for (int i = 1; i < grid_planningStaff.Rows.Count; i++)
{
grid_planningStaff.Rows[0].Visible = true;
grid_planningStaff.Rows[i].Visible = false;
}
}
//}
//catch (Exception)
//{
// throw;
//}
}
protected void yourgridview_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
this.FindControl("grdwv" + e.CommandArgument).Visible = false;
//i am assuming other gridview is on your .aspx page
}
}
Assuming you want to bind to an event on click, you just bind the method to the lkBtn.Click event:
LinkButton lkBtn = new LinkButton();
lkBtn.ForeColor = Color.Black;
lkBtn.Font.Underline = false;
lkBtn.ID = "link_button" + i;
lkBtn.Text = clientids;
lkBtn.CommandName = "Edit";
lkBtn.Click +=button_Click;
The method to handle the event:
void button_Click(object sender, EventArgs e)
{
//add code here for the button
}

Maintaining state and count of checkboxes while paging in a GridView control

I have a gridview on a aspx page with pagination enabled.
This gridview contains some data fields from a database and a check-box for each row.
I started out wondering whether the check-box option will be remembered if I rebind the datasource before looping through all the rows, but quickly determined that even going from one page to the next page then back again the check-box option is lost.
To persist the check box checked status I have tried a custom implementation in this tutorial: http://aspalliance.com/774_Maintaining_State_of_CheckBoxes_While_Paging_in_a_GridView_Control.all
I want to count the number of checkboxes which are checked on my asp.net page and if the count = 5 then to change the button state from disabled to enabled, but when I change page in Gridview are not counted the selected rows of the grid in previous page.
My code it's below.
I would greatly appreciate any help you can give me in working this problem.
private void RememberOldValues()
{
ArrayList categoryIDList = new ArrayList();
int index = -1;
foreach (GridViewRow row in GridView1.Rows)
{
index = (int)GridView1.DataKeys[row.RowIndex].Value;
bool result = ((CheckBox)row.FindControl("chkSelect")).Checked;
if (Session["CHECKED_ITEMS"] != null)
categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
if (result)
{
if (!categoryIDList.Contains(index))
categoryIDList.Add(index);
}
else
categoryIDList.Remove(index);
}
if (categoryIDList != null && categoryIDList.Count > 0)
Session["CHECKED_ITEMS"] = categoryIDList;
}
private void RePopulateValues()
{
ArrayList categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
if (categoryIDList != null && categoryIDList.Count > 0)
{
foreach (GridViewRow row in GridView1.Rows)
{
int index = (int)GridView1.DataKeys[row.RowIndex].Value;
if (categoryIDList.Contains(index))
{
CheckBox myCheckBox = (CheckBox)row.FindControl("chkSelect");
myCheckBox.Checked = true;
}
}
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
RememberOldValues();
GridViewBind();
GridView1.DataSource = dset.Tables[0];
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataBind();
RePopulateValues();
}
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
int count = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("chkSelect");
if (chk.Checked)
{
count++;
grdRow.BackColor = System.Drawing.Color.Yellow;
}
}
if (count == 5)
{
btnUpdate.Enabled = true;
btnUpdate.CssClass = "enabledImageButton";
}
else
{
btnUpdate.Enabled = false;
btnUpdate.CssClass = "disabledImageButton";
}
}
Declare a private property to read arralist from session, to avoid calling it again and again.
ArrayList SelectedCategories
{
get
{
ArrayList categoryIDList;
if (Session["CHECKED_ITEMS"] != null)
categoryIDList = (ArrayList)Session["CHECKED_ITEMS"];
else
{
categoryIDList = new ArrayList();
Session["CHECKED_ITEMS"] = categoryIDList;
}
return categoryIDList;
}
}
Then in your Checkbox changed event you can change the code to access the stored selection array list.
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chkTest = (CheckBox)sender;
GridViewRow grdRow = (GridViewRow)chkTest.NamingContainer;
int index = (int)GridView1.DataKeys[grdRow.RowIndex].Value;
if (chkTest.Checked)
{
if (!SelectedCategories.Contains(index))
SelectedCategories.Add(index);
grdRow.BackColor = System.Drawing.Color.Yellow;
}
else
{
if (SelectedCategories.Contains(index))
SelectedCategories.Remove(index);
grdRow.BackColor = System.Drawing.Color.White;
}
if (SelectedCategories.Count >= 5)
{
btnUpdate.Enabled = true;
btnUpdate.CssClass = "enabledImageButton";
}
else
{
btnUpdate.Enabled = false;
btnUpdate.CssClass = "disabledImageButton";
}
}

Redirect on select click in gridview

I have 2 GridViews with select rows enabled in my form. Can someone help me on coding where it can redirect to a different form on a click of a select in GridView instead of a button click (like I have coded)?
namespace TicketsApp
{
public partial class SearchTickets : System.Web.UI.Page
{
string connect = System.Configuration.ConfigurationManager.ConnectionStrings["TicketsConnectionString"].ConnectionString;
ArrayList selectedSportEvent = new ArrayList();
protected void btnSearch_Click1(object sender, EventArgs e)
{
DataAccess myData = new DataAccess();
ArrayList parameters = new ArrayList();
//Updates the selected by the dates specified
SqlDataReader results;
parameters.Add(new SqlParameter("#StartDate", CalStartDate.SelectedDate));
parameters.Add(new SqlParameter("#EndDate", CalEndDate.SelectedDate));
results = myData.GetDataReader("SearchTickets", connect, parameters);
//Clear sort expression
grdSearch.DataSourceID = String.Empty;
this.grdSearch.DataSource = results;
this.grdSearch.DataBind();
//makes gridview Search visible
grdSearch.Visible = true;
grdUpdated.Visible = false;
//make sure the dates are selected
if (CalStartDate.SelectedDate < DateTime.Today || CalEndDate.SelectedDate < DateTime.Today)
{
CalStartDate.Focus();
return;
}
if (CalEndDate.SelectedDate < DateTime.Today)
{
lblCalError.Visible = true;
return;
}
}
protected void btnUpdate_Click1(object sender, EventArgs e)
{
DataAccess myData = new DataAccess();
ArrayList parameters = new ArrayList();
//updates the selection by the sport selected
SqlDataReader results;
parameters.Add(new SqlParameter("#SportName", ddlSportType.SelectedItem.ToString()));
results = myData.GetDataReader("SearchTicketsBySport", connect, parameters);
//Clear sort expression
grdUpdated.DataSourceID = String.Empty;
this.grdUpdated.DataSource = results;
this.grdUpdated.DataBind();
//Makes gridview updated visible
grdUpdated.Visible = true;
grdSearch.Visible = false;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session.Remove("EventData");
}
CalStartDate.SelectedDate = DateTime.Today;
CalEndDate.SelectedDate = DateTime.Today;
}
//Adds the item selected to the array
protected void grdSearch_SelectedIndexChanged(object sender, EventArgs e)
{
selectedSportEvent.Clear();
int x;
for (x = 1; x < grdSearch.SelectedRow.Cells.Count; x++)
{
int selectedRow = grdSearch.SelectedIndex;
GridViewRow r = grdSearch.Rows[selectedRow];
Session["EventID"] = r.Cells[1].Text;
Session["description"] = r.Cells[2].Text;
Session["ticketcost"] = r.Cells[7].Text;
Session["numtickets"] = r.Cells[6].Text;
Session["State"] = r.Cells[9].Text;
Session["Section"] = r.Cells[4].Text;
Session["Row"] = r.Cells[5].Text;
Session["date"] = r.Cells[8].Text;
}
}
//Adds the item selected to the array
protected void grdUpdated_SelectedIndexChanged(object sender, EventArgs e)
{
selectedSportEvent.Clear();
int x;
for (x = 1; x < grdUpdated.SelectedRow.Cells.Count; x++)
{
int selectedRow = grdUpdated.SelectedIndex;
GridViewRow r = grdUpdated.Rows[selectedRow];
Session["EventID"] = r.Cells[1].Text;
Session["description"] = r.Cells[2].Text;
Session["ticketcost"] = r.Cells[7].Text;
Session["numtickets"] = r.Cells[6].Text;
Session["State"] = r.Cells[9].Text;
Session["Section"] = r.Cells[4].Text;
Session["Row"] = r.Cells[5].Text;
Session["date"] = r.Cells[8].Text;
}
}
protected void btnOrderTickets_Click(object sender, EventArgs e)
{
//Redirects to TicketOrder form
Response.Redirect("TicketOrder.aspx");
}
protected void CalStartDate_DayRender(object sender, DayRenderEventArgs e)
{
if (e.Day.Date < (System.DateTime.Now.AddDays(-1)))
{
e.Day.IsSelectable = false; e.Cell.Font.Strikeout = true;
}
}
}
}

Categories