Why ItemCommand doesn't fired on My Repeater - asp.net

please could anyone review my code and tell me what is the reason that itemCommand not getting fired on Buttons click.
<div class="">
<asp:Repeater ID="Repeater" runat="server" OnItemDataBound="Repeater_ItemDataBound" OnItemCommand="Repeater_ItemCommand">
<HeaderTemplate>
<div id="header" style="background-color:red">
</div>
</HeaderTemplate>
<ItemTemplate>
<div class="bms-car-item">
<div >
<image style="width:80px;height:60px" src="http://img2.netcarshow.com/Volkswagen-Golf_R32_2005_800x600_wallpaper_01.jpg"></image>
</div>
<div>
Car Type : <b> <%# DataBinder.Eval(Container.DataItem, "VehicleGroup") %> class or Similar </b>
</div>
<div>
Car Group: <b> <%# DataBinder.Eval(Container.DataItem, "SupplierGroup") %></b>
</div>
<div>
Properties:
<cp:CarProperties ID="CarPropertiesControl" runat="server" />
</div>
<div>
Price Before Voucher: <%# DataBinder.Eval(Container.DataItem, "PriceCust.Price") %> <%# DataBinder.Eval(Container.DataItem, "PriceCust.Currency") %>
</div>
<div>
Price per Rent:<b class="PricePlaceHolder"> <%# DataBinder.Eval(Container.DataItem, "PriceCust.Price") %> <%# DataBinder.Eval(Container.DataItem, "PriceCust.Currency") %></b>
</div>
<div>
<a href="#" onclick="return ShowTerms()" >Additional Info</a>
Options Included in Price
</div>
<asp:HiddenField ID="Selected" runat="server" value='<%# DataBinder.Eval(Container.DataItem, "VehicleModelCode") %>'></asp:HiddenField>
</div>
<div> <asp:Button Text="Select" ID="SelectButtonNext" CommandName="Get" runat="server" CommandArgument='<%# DataBinder.Eval(Container.DataItem, "VehicleModelCode") %>' /></div>
</ItemTemplate>
</asp:Repeater>
</div>
And relevant code behind class
protected void Page_Load(object sender, EventArgs e)
{
var state = SessionManager.GetReservationState();
//Load All Car Groups
if (!Page.IsPostBack)
{
LoadCurrencies();
LoadModels(state);
}
else
{
Repeater.DataBind();
}
}
private void LoadModels(BmsReservationHelper state)
{
if (state != null)
{
var carModels = BmsFascade.BmsFascade.GetCarsAndPrices(state.PickUpLocationCode.Trim(), state.PickUpTime.ToString(), state.ReturnTime.ToString(), "", "", "", "");
// TODO: Check what to do if BMS returning 0 cars avaliable ...
this.Repeater.DataSource = carModels.VehicleModels;
this.Repeater.DataBind();
var groups = carModels.VehicleModels.GroupBy(m => m.SupplierGroup).Select(m => m.FirstOrDefault());
foreach (var g in groups)
{
this.CarGroupsFilter.Items.Add(new ListItem(g.SupplierGroup, g.SupplierGroup));
}
}
}
private void LoadCurrencies()
{
this.CurrencyList.Items.Clear();
// Load All Currencies
var list = BmsFascade.BmsFascade.GetCurrencies();
foreach (var currencyPipe in list.ReturnValues)
{
string[] values = currencyPipe.Split('|');
this.CurrencyList.Items.Add(new ListItem(values[1], values[0]));
}
}
protected void Repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// Bind Car properties strip to the repeater control
if (e.Item.DataItem != null)
{
var model = e.Item.DataItem as BMSEntities.VehicleModelsBatchVehicleModel;
if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
{
// Trying to rebing command properties here ... no luck :-(
Button myButton = (Button)e.Item.FindControl("SelectButton");
myButton.CommandName = "Get";
myButton.CommandArgument = model.VehicleGroup;
}
BMS_BmsCarProperties_BmsCarProperties carProps = e.Item.FindControl("CarPropertiesControl") as BMS_BmsCarProperties_BmsCarProperties;
if (carProps != null)
{
// model.VehicleModelInfo.
carProps.LoadDataInfo(model);
}
}
}
protected void Repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
var x = e.CommandArgument;
Response.Write("fdsljknalsjndflkjasndflkjansdlkfjnasldkjnf");
}

The problem was in Base Page ... DataBind() for whole page was called without !ISPosback.

Related

Weird post back behavior on ASP.NET web form while refreshing

In an ASP.NET web form, I have two button controls and I have come across a weird scenario.
I have btnOpenAddRoleModal and btn2. when I click on btnOpenAddRoleModal, btnAddGlobalRoles becomes visible and then I click on btnAddGlobalRoles which performs some function.
Now when I press F5 to refresh the page, and because ASP.NET post-backs the page again on refresh, it does the post back as usual.
My problem is that it runs the click event handler of btnOpenAddRoleModal instead of btnAddGlobalRoles whereas the last button I clicked was btnAddGlobalRoles.
Anyone knows why this could be a case?
aspx page
<%# Page Title="" Language="C#" MasterPageFile="~/MasterPages/MainTheme.Master" AutoEventWireup="true" CodeBehind="GlobalRoles.aspx.cs" Inherits="OPT.GlobalRoles" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<header style="overflow: auto;">
<h1 class="zs-left">Global Roles</h1>
<div class="zs-right">
<asp:Button ID="btnOpenAddRoleModal" runat="server" Text="Add User" CssClass="zs-button zs-button-action" OnClick="btnOpenAddRoleModal_Click" OnClientClick="return IncreasePostBackControlValue();" />
</div>
</header>
<section class="page-2cols" style="position: relative;">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<h2 class="zs-inner-title">Roles</h2>
<p class="zs-search-button">
<span class="zs-input-icon zs-icon-search">
<asp:Label ID="lblSearchText" runat="server" Text="Search Roles " Style="font-weight: 700"></asp:Label>
<asp:TextBox ID="txtSearchText" runat="server" CssClass="zs-input" placehoder="Enter key words to search" AutoPostBack="True" OnTextChanged="txtSearchText_TextChanged"></asp:TextBox>
</span>
</p>
<p>
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label></p>
<p>
<asp:Label ID="lblNoResultsMessage" runat="server" Text="No results found" Visible="false"></asp:Label></p>
<p>
<asp:GridView ID="gvGlobalRoles" runat="server" AutoGenerateColumns="False" OnRowDeleting="gvGlobalRoles_RowDeleting" CssClass="zs-data-table">
<Columns>
<asp:BoundField DataField="Serial" HeaderText="Sr. No." />
<asp:BoundField DataField="EmployeeName" HeaderText="Employee Name" />
<asp:BoundField DataField="RoleName" HeaderText="Role" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<span class="zs-icon zs-icon-delete"></span>
<asp:LinkButton Text="Delete" CommandName="Delete" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</p>
<asp:Panel ID="pnlOverlay" CssClass="zs-overlay" Visible="false" runat="server"></asp:Panel>
<asp:Panel ID="pnlModal" Visible="false" CssClass="zs-modal" Style="display: inline-block; position: fixed; top: 50%; left: 50%; margin-top: 0px; margin-left: 0px; transform: translate(-50%, -50%);" runat="server">
<header>
<span><% =ModalTitle %></span>
<asp:LinkButton ID="lbCloseModal" runat="server" CssClass="zs-icon zs-icon-close zs-icon-large" OnClick="lbCloseModal_Click"></asp:LinkButton>
</header>
<section>
<p>
<asp:Label ID="lblModalMessage" runat="server" Text=""></asp:Label></p>
<asp:Panel ID="pnlDeleteListItem" runat="server" Visible="false">
You have selected to delete a role. Press OK to continue or Cancel to abort.
</asp:Panel>
<asp:Panel ID="pnlAddEditListItem" runat="server" Visible="false">
<p>
<asp:Label ID="lblEmployeeToAdd" runat="server" Text="Employee Email"></asp:Label><br />
<asp:TextBox ID="txtEmployeeToAdd" runat="server" CssClass="zs-input"></asp:TextBox>
</p>
<p>
<asp:Label ID="lblRoleToAdd" runat="server" Text="Role"></asp:Label><br />
<asp:DropDownList ID="ddlRoleToAdd" runat="server" CssClass="zs-input"></asp:DropDownList>
</p>
</asp:Panel>
</section>
<footer>
<asp:LinkButton ID="lbCancelModal" runat="server" OnClick="lbCancelModal_Click">Cancel</asp:LinkButton>
<asp:Button ID="btnAddGlobalRoles" runat="server" Text="Add" CssClass="zs-button zs-button-action" OnClick="btnAddGlobalRoles_Click" OnClientClick="return IncreasePostBackControlValue();" Visible="false" />
<asp:Button ID="btnDeleteGlobalRole" runat="server" CssClass="zs-button zs-button-action" Text="OK" OnClick="btnDeleteGlobalRole_Click" OnClientClick="return IncreasePostBackControlValue();" Visible="false" />
</footer>
</asp:Panel>
<asp:HiddenField ID="hfPostBackControl" runat="server" ClientIDMode="Static" />
<script>
//$(document).on("click", "button,input[type='submit'],input[type='button']", function () {
// $("#hfPostBackControl").val($("#hfPostBackControl").val() == "" ? 1 : Number($("#hfPostBackControl").val()) + 1);
//});
function IncreasePostBackControlValue() {
$("#hfPostBackControl").val($("#hfPostBackControl").val() == "" ? 1 : Number($("#hfPostBackControl").val()) + 1);
return true;
}
</script>
</ContentTemplate>
</asp:UpdatePanel>
</section>
</asp:Content>
aspx.cs page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using OPT.Models;
namespace OPT
{
public partial class GlobalRoles : System.Web.UI.Page
{
BAL bal = new BAL();
string message = "";
int messageStateID;
DataTable dtRoles;
DataTable dtGlobalEmployeeRoles;
GlobalRole globalRoleToDelete;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadRoleDropDown();
LoadGlobalRolesFromDatabase();
Session["sPostBackValue"] = 0;
}
Generic.HideControls(AllMessageControls);
}
protected void Page_PreInit(object sender, EventArgs e)
{
Session["CurrentPage"] = ePage.GlobalRoles;
}
protected void Page_LoadComplete(object sender, EventArgs e)
{
if (!Pages.ShowGlobalRoles())
{
Generic.RediretToMesagePage("Unauthorized user");
}
if (gvGlobalRoles.Rows.Count > 0)
{
gvGlobalRoles.HeaderRow.TableSection = TableRowSection.TableHeader;
lblNoResultsMessage.Visible = false;
}
else
{
lblNoResultsMessage.Visible = true;
}
}
void LoadGlobalRolesFromDatabase()
{
dtGlobalEmployeeRoles = bal.GetGlobalEmployeeRoles(txtSearchText.Text, ref message, ref messageStateID);
Session["GlobalEmployeeRoles"] = dtGlobalEmployeeRoles;
gvGlobalRoles.DataSource = Session["GlobalEmployeeRoles"] as DataTable;
gvGlobalRoles.DataBind();
}
void LoadRoleDropDown()
{
dtRoles = bal.GetGlobalRoles(ref message, ref messageStateID);
Generic.PopulateDataTableInDropDown(ddlRoleToAdd, dtRoles, "ID", "Name", "Please select");
}
protected void gvGlobalRoles_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int rowIndex = e.RowIndex;
globalRoleToDelete = new GlobalRole();
dtGlobalEmployeeRoles = Session["GlobalEmployeeRoles"] as DataTable;
globalRoleToDelete.ID = Convert.ToInt32(dtGlobalEmployeeRoles.Rows[rowIndex]["ID"].ToString());
Session["CurrentGlobalRole"] = globalRoleToDelete;
ModalTitle = "Delete Role";
Generic.ShowControls(modalDeleteControls);
}
protected void btnAddGlobalRoles_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
Employee employee = new Employee();
Role role = new Role();
employee.EmailID = txtEmployeeToAdd.Text;
role.ID = Convert.ToInt32(ddlRoleToAdd.SelectedValue);
bal.CreateGlobalEmployeeRole(employee, role, ref message, ref messageStateID);
if (messageStateID == 1)
{
Generic.HideControls(modalAllControls);
Generic.ShowMessage(lblMessage, message, messageStateID);
}
else
{
ModalTitle = eModalTitle.EditProject;
Generic.ShowMessage(lblModalMessage, message, messageStateID);
}
LoadGlobalRolesFromDatabase();
}
protected void btnDeleteGlobalRole_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
globalRoleToDelete = Session["CurrentGlobalRole"] as GlobalRole;
bal.DeleteGlobalEmployeeRole(globalRoleToDelete, ref message, ref messageStateID);
if (messageStateID == 1)
{
Generic.HideControls(modalAllControls);
Generic.ShowMessage(lblMessage, message, messageStateID);
}
else
{
ModalTitle = eModalTitle.EditProject;
Generic.ShowMessage(lblModalMessage, message, messageStateID);
}
LoadGlobalRolesFromDatabase();
Generic.HideControls(modalDeleteControls);
}
protected void lbCloseModal_Click(object sender, EventArgs e)
{
Generic.HideControls(modalAllControls);
}
protected void lbCancelModal_Click(object sender, EventArgs e)
{
Generic.HideControls(modalAllControls);
}
protected void btnOpenAddRoleModal_Click(object sender, EventArgs e)
{
if (Generic.IsRefresh(hfPostBackControl)) { return; }
ModalTitle = "Add Role";
Generic.ClearControlValuesInContainer(pnlAddEditListItem);
Generic.ShowControls(modalAddControls);
}
protected void txtSearchText_TextChanged(object sender, EventArgs e)
{
LoadGlobalRolesFromDatabase();
}
private string _ModalTitle;
public string ModalTitle
{
get { return _ModalTitle; }
set { _ModalTitle = value; }
}
protected List<Control> modalAllControls
{
get
{
List<Control> controls = new List<Control>();
controls.AddRange(modalGenericControls);
controls.AddRange(modalAddControls);
controls.AddRange(modalDeleteControls);
return controls;
}
}
protected List<Control> modalGenericControls
{
get
{
return new List<Control>{
pnlOverlay as Control,
pnlModal as Control
};
}
}
protected List<Control> modalDeleteControls
{
get
{
List<Control> controls = new List<Control>{
pnlDeleteListItem as Control,
btnDeleteGlobalRole as Control
};
controls.AddRange(this.modalGenericControls);
return controls;
}
}
protected List<Control> modalAddControls
{
get
{
List<Control> controls = new List<Control>{
pnlAddEditListItem as Control,
btnAddGlobalRoles as Control
};
controls.AddRange(this.modalGenericControls);
return controls;
}
}
protected List<Control> AllMessageControls
{
get
{
List<Control> messageControls = new List<Control>{
lblMessage as Control,
lblModalMessage as Control
};
return messageControls;
}
}
}
}
Few supporting methods here
public static bool IsRefresh(HiddenField hfPostBackControl)
{
int sPostBackValue = HttpContext.Current.Session["sPostBackValue"] == null ? 0 : Convert.ToInt32(HttpContext.Current.Session["sPostBackValue"]);
int hPostBackValue = string.IsNullOrEmpty(hfPostBackControl.Value) ? 0 : Convert.ToInt32(hfPostBackControl.Value);
HttpContext.Current.Session["sPostBackValue"] = hPostBackValue;
return sPostBackValue == hPostBackValue;
}
/// <summary>
/// This method can be used for displaying pop ups after any action. One needs to pass the controls as parameter that need to shown on any event.
/// </summary>
/// <param name="controls">List of controls that need to be displyed as pop-up</param>
public static void ShowControls(List<Control> controls)
{
foreach (Control c in controls)
{
c.Visible = true;
}
}
/// <summary>
/// This method can be used for hiding pop ups being displayed. One needs to pass the controls as parameter that need to hidden on any event.
/// </summary>
/// <param name="controls">List of controls that need to be hidden</param>
public static void HideControls(List<Control> controls)
{
foreach (Control c in controls)
{
c.Visible = false;
}
}
public static void ShowMessage(Label lblMessage, string message, int messageStateID)
{
lblMessage.Text = message;
lblMessage.CssClass = messageStateID == 1 ? "zs-message zs-success" : "zs-message zs-error";
lblMessage.Visible = true;
}

Dynamic user control loses data while switching between views in multiview

I have a MultiView with two views (first one with form and second one to review data entered in first view). First view contains a TextBox and a PlaceHolder. The PlaceHolder is used to hold dynamically added add UserControl. UserControl contains DropDownList(s), TextBox, and CheckBox.
Working fine: Currently I can add new user control in the page through a Add button, which causes the page to PostBack but I do not lose any data in existing dynamic UserControl.
Issue: When I toggle between the views (using SetActiveView), I lose data in dynamically added user control but the data in the static TextBox remains intact.
Following I have the code snippet.
<%# Page Title="" Language="C#" MasterPageFile="~/M.master" AutoEventWireup="true" CodeFile="test.aspx.cs" Inherits="test" %>
<%# Reference Control="dynamic_uc.ascx" %>
<%# Register src="dynamic_uc.ascx" tagname="ucrange" tagprefix="uc1" %>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<div class="light_blue_background pad10 helvetica innerpad5">
<asp:MultiView ID="mv_main" runat="server" ActiveViewIndex="0">
<asp:View ID="vu_add" runat="server">
<table>
<tr style="border-bottom: 1px solid #ccc;">
<td>
Name:
</td>
<td>
<asp:TextBox ID="txt_Name" runat="server" Columns="50" MaxLength="35" />
</td>
</tr>
</table>
<asp:Panel ID="pnl_TempRange_" runat="server">
</asp:Panel>
<asp:PlaceHolder ID="pl_Range" runat="server"></asp:PlaceHolder>
</asp:View>
<asp:View ID="vu_review" runat="server">
review your data
</asp:View>
</asp:MultiView>
<asp:Button ID="btn_addRange" runat="server" Text="Add Range"
CausesValidation="False" onclick="btn_addRange_Click" />
<asp:Button ID="btn_submit" runat="server" Text="Submit"
onclick="btn_submit_Click" />
<asp:Button ID="btn_modify" runat="server" Text="Modify"
onclick="btn_modify_Click" Visible="false"/>
</div>
</asp:Content>
C# Code:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
public partial class Test : System.Web.UI.Page
{
private static int ControlCount=0;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ControlCount = 0;
}
AddControls();
foreach (Control c in pnl_TempRange.Controls)
{
DropDownList ddl_UpLimit = (DropDownList)c.FindControl("ddl_Uplimit");
PopulateDropdownRange(ddl_UpLimit, 0, 100);
DropDownList ddl_LowLimit = (DropDownList)c.FindControl("ddl_Lowlimit");
PopulateDropdownRange(ddl_LowLimit, 0, 100);
}
Response.Write(tests);
}
public static Control GetPostBackControl(Page page)
{
Control control = null;
string ctrlname = page.Request.Params.Get("__EVENTTARGET");
if (ctrlname != null && ctrlname != string.Empty)
{
control = page.FindControl(ctrlname);
}
else
{
foreach (string ctl in page.Request.Form)
{
Control c = page.FindControl(ctl);
if (c is System.Web.UI.WebControls.Button)
{
control = c;
break;
}
}
}
return control;
}
private void AddControls()
{
int ID = 0;
Control cd = GetPostBackControl(Page);
if ((c != null))
{
if (c.ID.ToString() == "btn_addRange")
{
dynamic_uc++;
}
}
pl_Range.Controls.Clear();
for (int i = 0; i <= tempControlCount; i++)
{
Range DynamicUserControl = (Range)Page.LoadControl("dynamic_uc.ascx");
while (IsInDeletedLog("uc" + ID) == true)
{
ID += 1;
}
DynamicUserControl.ID = "dyn_uc" + ID;
DynamicUserControl.RemoveTempControl += this.HandleRemoveTempRange;
pl_Range.Controls.Add(DynamicUserControl);
ID += 1;
}
}
protected void btn_addRange_Click(object sender, EventArgs e)
{
}
private void PopulateDropdownRange(DropDownList ddl, int rangeMin, int rangeMax)
{
ddl.Items.Clear();
ddl.Items.Add("--Select--");
for (int i = rangeMin; i <= rangeMax; i++)
{
ddl.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
}
private void BindDDl(DropDownList ddl,string strQuery)
{
ddl.DataSource = GetDataFromQuery(strQuery);
ddl.DataValueField = "VALUE";
ddl.DataTextField = "NAME";
ddl.DataBind();
ddl.Items.Insert(0,"--Select--");
}
protected void btn_submit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
mv_main.SetActiveView(vu_reviewCmpd);
btn_submitCompound.Visible = false;
btn_confirmCompound.Visible = true;
btn_modifyCompound.Visible = true;
}
}
protected void btn_modify_Click(object sender, EventArgs e)
{
mv_main.SetActiveView(vu_add);
btn_submit.Visible = true;
btn_confirm.Visible = false;
btn_modify.Visible = false;
}
Thanks for the help.

Custom pager control

I develop a custom data pager control. Its "previous" and "next" hyperLink buttons don't work properly and I don't understand why.
<asp:Repeater ID="rpt" runat="server">
<HeaderTemplate>
<asp:LinkButton ID="lnkbFirst" CommandName="<%#PageChangedItemCommand %>" CommandArgument="1" runat="server">«</asp:LinkButton>
<asp:LinkButton ID="lnkbPrevious" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#PreviousPageIndex%>" runat="server"><</asp:LinkButton>
</HeaderTemplate>
<ItemTemplate>
<asp:LinkButton CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#Container.DataItem.ToString()%>" ID="p" runat="server" ><%#Container.DataItem.ToString()%> </asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lnkbNext" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#NextPageIndex%>" runat="server">></asp:LinkButton>
<asp:LinkButton ID="lnkbLast" CommandName="<%#PageChangedItemCommand %>" CommandArgument="<%#PagesCount%>" runat="server">»</asp:LinkButton>
</FooterTemplate>
</asp:Repeater>
public partial class Pager : System.Web.UI.UserControl
{
public int CurrentPage { get; set; }
public int PageSize { get; set; }
public int DataItemsCount { get; set; }
private int _pagesCount;
public int PagesCount
{
get
{
if (DataItemsCount % PageSize == 0)
return _pagesCount = (DataItemsCount / PageSize);
else
return _pagesCount = ((DataItemsCount / PageSize) + 1);
}
private set
{
_pagesCount = value;
}
}
public event EventHandler<PageChangedEventArgs> PageChanged;
protected const string PageChangedItemCommand = "PageChanged";
private const string CurrentPageCssStyle = "font-weight:bold; font-size:15px;";
private void RaiseEvent(int currentPage)
{
if (PageChanged != null)
PageChanged(this, new PageChangedEventArgs(currentPage));
}
protected List<int> DataSource
{
get
{
List<int> pages = new List<int>();
for (int i = 1; i <= PagesCount; i++)
pages.Add(i);
return pages;
}
}
protected int NextPageIndex { get { return CurrentPage + 1; } }
protected int PreviousPageIndex { get { return CurrentPage -1; } }
public Pager()
{
CurrentPage = 1;
PageSize = 1;
DataItemsCount = 1;
}
protected void Page_Load(object sender, EventArgs e)
{
rpt.ItemCommand += new RepeaterCommandEventHandler(rpt_ItemCommand);
rpt.DataSource = DataSource;
rpt.DataBind();
//
if (!Page.IsPostBack)
{
CurrentPageSetCssStyle(CurrentPageCssStyle);
// SetupCommandArguments();
}
}
void rpt_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == PageChangedItemCommand)
{
CurrentPage = int.Parse(e.CommandArgument.ToString());
CurrentPageSetCssStyle(CurrentPageCssStyle);
// SetupCommandArguments();
RaiseEvent(CurrentPage);
}
}
private void CurrentPageSetCssStyle(string style)
{
foreach (RepeaterItem item in rpt.Items)
{
LinkButton lnkButton = item.FindControl("p") as LinkButton;
if (lnkButton != null)
{
if (lnkButton.CommandArgument == CurrentPage.ToString())
lnkButton.Attributes.Add("style", style);
}
}
// SetupCommandArguments();
}
void SetupCommandArguments()
{
LinkButton lnkbPrevious = rpt.Controls[0].Controls[0].FindControl("lnkbPrevious") as LinkButton;
if (lnkbPrevious != null)
lnkbPrevious.CommandArgument = (CurrentPage - 1).ToString();
LinkButton lnkbNext = rpt.Controls[rpt.Controls.Count - 1].Controls[0].FindControl("lnkbNext") as LinkButton;
if (lnkbPrevious != null)
lnkbPrevious.CommandArgument = (CurrentPage + 1).ToString();
}
}
I need to develop my own paging light control. Don't suggest me to use other paging controls.
I've had to do a custom pager in the last few days, but I went about it slightly differently.
I chose to use two repeaters:
1. This one was for the paging
<div class="searchResultsPaging" runat="server">
<asp:Repeater ID="Paging" runat="server">
<ItemTemplate>
<a href='<%# Eval("PageUrl") %>' class='<%# (Convert.ToBoolean(Eval("IsCurrent")) == true)? "pagingButtonOff" : "pagingButtonOn" %>'>
<%# Eval("PageText") %></a>
</ItemTemplate>
</asp:Repeater>
</div>
2. Was for the items I'm display
<asp:Repeater ID="Properties" runat="server">
<ItemTemplate>
<div class="propertyCard">
<div class="propertyTitle">
<a href='/property/<%# Eval("Id") %>'>
<%# Eval("Title") %></a></div>
<div class="propertySuburb">
<%# Eval("Suburb") %></div>
<img src='/_Remove/SamplePropertyImages/<%# Eval("PriorityImage") %>' width="190"
height="143" alt='Property for sale in <%# Eval("Suburb")%>' />
<div class="propertyFeatures">
<img src="/_Remove/Icons/Bed.gif" alt='<%# Eval("Suburb") %>, <%# Eval("City") %> property has <%# Eval("Bedrooms") %> bedrooms.' /><%# Eval("Bedrooms") %><img
src="/_Remove/Icons/Bath.gif" alt='<%# Eval("Suburb") %>, <%# Eval("City") %> property has <%# Eval("Bathrooms") %> bedrooms.' /><%# Eval("Bathrooms") %></div>
<div class="propertyPrice">
<%# Eval("Price","{0:###,##0.00}") %>
</div>
View Property Details
</div>
</ItemTemplate>
</asp:Repeater>
During binding, my business logic returned a list of properties and a total count. From there it was easy to bind and build the paging controls.
Might not work for you since you're looking for page next/back type functionality.
Regards,
Jacqueds

ASP.NET is it possible to access public page variables from ListView.EmptyDataTemplate?

is it possible to access public page variables from ListView.EmptyDataTemplate ?
Can i do that and if can, how ?
thanks
Basically with:
<%= this.YourPagesPublicProperty%>
Example, my ASP.NET File:
<p>IntDicIsEmptyValue: <%= this.IntDicIsEmptyValue %></p>
<asp:ListView ID="ListView1" runat="server" >
<LayoutTemplate>
<ul runat="server" id="itemPlaceholder"></ul>
</LayoutTemplate>
<ItemTemplate>
<p><%# Eval("Key") %> / <%# Eval("Value") %></p>
</ItemTemplate>
<EmptyDataTemplate>
<p>Status: <%= this.IntDicIsEmptyValue%></p>
</EmptyDataTemplate>
</asp:ListView>
And my .cs File:
public Dictionary<int,string> intdic;
public string IntDicIsEmptyValue { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
IntDicIsEmptyValue = "Is Empty";
intdic = new Dictionary<int, string>();
//Comment next two lines to see Emptydatatemplate with IsEmpty
intdic.Add(3, "Three");
intdic.Add(4, "Four");
ListView1.DataSource = intdic;
ListView1.DataBind();
}

Using Repeater for an updateable form

I have a list of parameter names for which I want a user to type in some values, so I do this:
<div>
<asp:Repeater runat="server" ID="rptTemplateParams" EnableViewState="true">
<HeaderTemplate>
<ul>
</HeaderTemplate>
<ItemTemplate>
<li>
<asp:Label runat="server"><%#Container.DataItem%></asp:Label>
<asp:TextBox runat="server" ID="textParamValue"></asp:TextBox>
</li>
</ItemTemplate>
<FooterTemplate>
</ul>
</FooterTemplate>
</asp:Repeater>
</div>
<asp:Button runat="server" ID="Send" Text="Send Email" OnClick="Send_Click" />
and on server side:
void Page_Load(...)
{
rptTemplateParams.DataSource =Params; // Params is List<string>
rptTemplateParams.DataBind();
}
public void Send_Click(object sender, EventArgs e)
{
ParamDict = new Dictionary<string, string>();
foreach (RepeaterItem item in rptTemplateParams.Items)
{
if (item.ItemType == ListItemType.Item)
{
TextBox textParamValue = (TextBox)item.FindControl("textParamValue");
if (textParamValue.Text.Trim() != String.Empty)
{
// IT NEVER GETS HERE - textParamValue.Text IS ALWAYS EMPTY!!!
ParamDict.Add(item.DataItem.ToString(), textParamValue.Text);
}
}
}
}
As I put in the comment, i can't retrieve text box values - they are always empty. Am I retrieving those in the wrong place?
Thanks!
Andrey
Try modifying your page_load like this
if(!Page.IsPostBack)
{
rptTemplateParams.DataSource =Params; // Params is List<string>
rptTemplateParams.DataBind();
}
The databinding wipes out existing controls and replaces them with new blank controls. You only want to databind when necessary.
try this:
void Page_Load(...)
{
if (!IsPostBack)
{
rptTemplateParams.DataSource =Params; // Params is List<string>
rptTemplateParams.DataBind();
}
}

Resources