asp.net中Repeater控件用法筆記
來(lái)源:易賢網(wǎng) 閱讀:604 次 日期:2015-01-14 15:38:49
溫馨提示:易賢網(wǎng)小編為您整理了“asp.net中Repeater控件用法筆記”,方便廣大網(wǎng)友查閱!

大家可能都對(duì)datagrid比較熟悉,但是如果在數(shù)據(jù)量大的時(shí)候,我們就得考慮使用repeater作為我們的數(shù)據(jù)綁定控件了。Repeater控件與DataGrid (以及DataList)控件的主要區(qū)別是在于如何處理HTML。ASP.NET建立HTML代碼以顯示DataGrid控件,但Repeater允許開(kāi)發(fā)人員決定如何顯示數(shù)據(jù)。所以,你可以選擇將數(shù)據(jù)顯示在一個(gè)HTML表格中或者一個(gè)順序列表中。這主要取決于你的選擇,但你必須將正確的HTML插入到 ASP.NET頁(yè)面中。

模板與DataList一樣,Repeater控件只支持模板。以下的模板可供選擇:

AlternatingItemTemplate: 指定如何顯示每一其它選項(xiàng)。

ItemTemplate: 指定如何顯示選項(xiàng)。(AlternatingItemTemplate可以覆蓋這一模板。)

HeaderTemplate: 建立如何顯示標(biāo)題。

FooterTemplate: 建立如何顯示頁(yè)腳。

SeparatorTemplate: 指定如何顯示不同選項(xiàng)之間的分隔符。

你可以使用這些模板來(lái)顯示你希望的數(shù)據(jù)。唯一具有強(qiáng)制性的模板是ItemTemplate,所有其它的模板都是具有選擇性的。

對(duì)于處理一個(gè)數(shù)據(jù)源,Repeater控件具有與DataGrid與DataList相同的屬性:

DataMember:獲得或者設(shè)置與 Repeater 控件綁定的相應(yīng)DataSource屬性的表格。

DataSource:獲得或者設(shè)置為 Repeater 顯示提供數(shù)據(jù)的數(shù)據(jù)源。

除此之外,還有一個(gè)Items屬性,你可以通過(guò)這一屬性編程訪(fǎng)問(wèn)Repeater數(shù)據(jù)中單一選項(xiàng)。它返回一個(gè)RepeaterItemCollection對(duì)象,為一組RepeaterItem對(duì)象的集合,代表 Repeater 數(shù)據(jù)的每一行。

ASP.NET Web數(shù)據(jù)控件還有其它一個(gè)共性:它們都使用DataBind方法來(lái)生成用戶(hù)界面。調(diào)用這一方法可以返回并顯示數(shù)據(jù)(假設(shè)DataSource和 DataMember屬性設(shè)置正確)。在查看DataBind方法之前,我們先看看如何在一個(gè)Web頁(yè)面中使用一個(gè)Repeater控件。

使用Repeater控件

使用Repeater控件的第一步驟是決定我們將要使用的數(shù)據(jù)源和字段。例如,我們將要使用SQL Server Northwind數(shù)據(jù)庫(kù)中的Employees列表。Web頁(yè)面將顯示職工的完整名字,地址,以及電話(huà)號(hào)碼。HTML將使用DIV標(biāo)記,用 Repeater 模板來(lái)分隔內(nèi)容。下面是 Web 頁(yè)面的 HTML 內(nèi)容:

前臺(tái)代碼

代碼如下

<asp:Repeater ID="Repeater1" runat="server">

<HeaderTemplate><table cellpadding="0" cellspacing="0" border="1" align="center" class="auto-style1">

<tr align="left">

<th>編號(hào)</th>

<th>姓名</th>

<th>年齡</th>

<th>班級(jí)</th>

<th>零花</th>

</tr>

</HeaderTemplate>

<ItemTemplate>

<tr >

<td><%#Eval("id")%></td>

<td><%#Eval("name")%></td>

<td><%#Eval("age")%></td>

<td><%#Eval("classid")%></td>

<td><%#Eval("salary")%></td>

</tr>

</ItemTemplate>

<FooterTemplate></table></FooterTemplate>

</asp:Repeater>

后臺(tái)代碼

代碼如下

string sql = string.Format("select * from person");

DataTable dt = sqlhelper.helper.ExecuteQuery(sql);

Repeater1.DataSource = dt;

Repeater1.DataBind();

AspNetpager的使用方法:

首先注冊(cè)<%@ Register Assembly="AspNetPager" Namespace="Wuqi.Webdiyer" TagPrefix="webdiyer" %>

前臺(tái):

代碼如下

<webdiyer:AspNetPager ID="AspNetPager1" runat="server" CustomInfoHTML="第%CurrentPageIndex%頁(yè),共%PageCount%頁(yè),每頁(yè)%PageSize%條"

FirstPageText="首頁(yè)" LastPageText="尾頁(yè)" LayoutType="Table" NextPageText="下一頁(yè)"

onpagechanging="AspNetPager1_PageChanging" PageIndexBoxType="DropDownList"

PagingButtonLayoutType="Span" PrevPageText="上一頁(yè)" ShowCustomInfoSection="Left"

ShowPageIndexBox="Always" SubmitButtonText="Go" TextAfterPageIndexBox="頁(yè)"

TextBeforePageIndexBox="轉(zhuǎn)到" Width="450px" PageSize="3">

</webdiyer:AspNetPager>

后臺(tái):

代碼如下

private void AddPages(Repeater rpt,Wuqi.Webdiyer.AspNetPager anp,DataTable dt)

{

PagedDataSource pds = new PagedDataSource();

pds.AllowPaging = true;

pds.DataSource = dt.DefaultView;

anp.RecordCount = dt.Rows.Count;//給分頁(yè)控件指定當(dāng)前總數(shù)

pds.PageSize = anp.PageSize;//確定分頁(yè),每頁(yè)有n項(xiàng)

pds.CurrentPageIndex = anp.CurrentPageIndex - 1;//確定當(dāng)前頁(yè)數(shù)

rpt.DataSource = pds;//綁定數(shù)據(jù)源

rpt.DataBind();

}

protected void AspNetPager1_PageChanging(object src, Wuqi.Webdiyer.PageChangingEventArgs e)

{

AspNetPager1.CurrentPageIndex = e.NewPageIndex;

BindPersonData();

}

例子

repeater控件動(dòng)態(tài)添加、刪除一行

代碼如下

<script type="text/javascript">

var txtEquipmentIdsIDArray = new Array();

function OpenWindow(clientId, TypeId, ReqNum) {

var url = "../EquipmentIssue/EquipmentRequestIssue.aspx?TypeId=" + TypeId + "&ReqNum=" + ReqNum;

var widths = 600;

var heigths = 450;

var winPar = window.showModalDialog(url, window, 'dialogWidth=' + widths + 'px;dialogHeight=' + heigths + 'px;status=no;center=yes;scroll=no;help:No;');

if (winPar != undefined) {

var txtEquipmentIds = document.getElementById(clientId);

txtEquipmentIds.value = winPar;

// //審批用戶(hù)控件中保存發(fā)放的EquipmentId

// var IsExistEquipmentIdsID = false;

// for (var i = 0; i < txtEquipmentIdsIDArray.length; i++) {

// if (txtEquipmentIdsIDArray[i] == clientId) {

// IsExistEquipmentIdsID = true;

// }

// }

// if (IsExistEquipmentIdsID == false) {

// txtEquipmentIdsIDArray.push(clientId);

// }

// var tempEquipmentId = "";

// for (var i = 0; i < txtEquipmentIdsIDArray.length; i++) {

// tempEquipmentId = tempEquipmentId + document.getElementById(txtEquipmentIdsIDArray[i]).value;

// var hiddenEquipmentIds = document.getElementById("UC_ApprovalAction1_hfEquipmentIds");

// hiddenEquipmentIds.value = tempEquipmentId;

// }

// //alert(hiddenEquipmentIds.value);

}

var tempReturnValue = "";

var tb_Request = document.getElementById("tb_Request");

var tr = tb_Request.getElementsByTagName("tr");

for (var i = 0; i < tr.length; i++) {

if (tr[i].id != "") {

var span_EquRequestItemId = tr[i].getElementsByTagName("span"); //獲取申請(qǐng)明細(xì)的IDEquRequestItemId

var select_ddlStation; //獲取使用工位StationId

var option = tr[i].getElementsByTagName("select")[1].getElementsByTagName("option");

for (var j = 0; j < option.length; j++) {

if (option[j].selected)

{

select_ddlStation = option[j]

}

}

var textarea_EquipmentIds = tr[i].getElementsByTagName("textarea"); //獲取發(fā)放的資產(chǎn)號(hào)EquipmentNo

tempReturnValue = tempReturnValue + span_EquRequestItemId[0].innerText + ":" + select_ddlStation.value + ":" + textarea_EquipmentIds[0].innerText + "|";

}

}

var hiddenEquipmentIds = document.getElementById("UC_ApprovalAction1_hfEquipmentIds");

hiddenEquipmentIds.value = tempReturnValue;

//alert(hiddenEquipmentIds.value);

}

</script>

Repeater:

代碼如下

<div id="div_Repeater">

<asp:HiddenField ID="hfRptColumns" runat="server" Value="Guid,EquRequestItemId,EquipmentType,Station,EquipmentNum,EquipmentIds" />

<table id="tb_Request" cellpadding="1" cellspacing="0" width="100%" style="background-color: #DFE8F6; font-size:12px; padding:10px;">

<thead>

<tr>

<th>序號(hào)</th>

<th>明細(xì)編號(hào)</th>

<th>

資產(chǎn)類(lèi)型

</th>

<th>

使用工位

</th>

<th>

申請(qǐng)數(shù)量

</th>

<th>

發(fā)放的資產(chǎn)號(hào)<font color="red">(資產(chǎn)管理員填寫(xiě))</font>

</th>

</tr>

</thead>

<tbody>

<asp:Repeater ID="rptRequest" runat="server" onitemcommand="rptRequest_ItemCommand"

onitemdatabound="rptRequest_ItemDataBound">

<ItemTemplate>

<tr id="tr_Request">

<td>

<%# Container.ItemIndex+1 %>

<asp:Label ID="lblGuid" runat="server" Text='<%#Eval("Guid") %>' Visible="false"></asp:Label>

</td>

<td><asp:Label ID="lblEquRequestItemId" runat="server" Text='<%#Eval("EquRequestItemId") %>'></asp:Label></td>

<td>

<asp:DropDownList ID="ddlEquipmentType" runat="server"></asp:DropDownList>

<asp:Label ID="lblEquipmentType" runat="server" Text='<%#Eval("EquipmentType") %>' Visible="false"></asp:Label>

</td>

<td>

<asp:DropDownList ID="ddlStation" runat="server"></asp:DropDownList>

<asp:Label ID="lblStation" runat="server" Text='<%#Eval("Station") %>' Visible="false"></asp:Label>

</td>

<td><asp:TextBox ID="txtReqEquipmentNum" runat="server" Text='<%#Eval("EquipmentNum") %>'></asp:TextBox></td>

<td><asp:TextBox ID="txtEquipmentIds" runat="server" Text='<%#Eval("EquipmentIds") %>' TextMode="MultiLine"></asp:TextBox></td>

<td><asp:Button ID="btnAddRow" runat="server" Text="新增一行" CommandName="add" />

&nbsp;&nbsp;&nbsp;&nbsp;<asp:Button ID="btnDeleteRow" runat="server" Text="刪除本行" CommandName="delete" /></td>

</tr>

</ItemTemplate>

</asp:Repeater>

</tbody>

</table>

</div>

后臺(tái):

代碼如下

/// <summary>

/// 綁定repeater的數(shù)據(jù)源

/// </summary>

private void RepeaterBindData()

{

DataTable dt = DefineDataTableSchema(hfRptColumns.Value);

if (Request["BusinessNo"] == null)

{

LoadData(dt);

}

else

{

LoadData(Request["BusinessNo"].ToString(), dt);

}

rptRequest.DataSource = dt;

rptRequest.DataBind();

}

private void LoadData(string businessNo, DataTable dt)

{

string strSql = "select * from EMS_EquipmentRequestItem where BussinessNo = '"+ businessNo +"'";

DataTable dt_EquipmentRequestItem = DBUtility.DbHelperSQL.Query(strSql).Tables[0];

//for (int i = 0; i < dt_EquipmentRequestItem.Rows.Count; i++)

foreach (DataRow dr in dt_EquipmentRequestItem.Rows)

{

DataRow row = dt.NewRow();

row["Guid"] = Guid.NewGuid();

row["EquRequestItemId"] = dr["EquRequestItemId"].ToString();

row["EquipmentType"] = dr["TypeId"].ToString();

row["Station"] = dr["StationId"].ToString();

row["EquipmentNum"] = dr["EquipmentNum"].ToString();

row["EquipmentIds"] = dr["EquipmentIds"].ToString();

dt.Rows.Add(row);

}

}

/// <summary>

/// repeater數(shù)據(jù)默認(rèn)加載

/// </summary>

/// <param name="dt"></param>

private void LoadData(DataTable dt)

{

//默認(rèn)顯示1行

for (int i = 0; i < 1; i++)

{

DataRow row = dt.NewRow();

dt.Rows.Add(row);

}

//為第一行加載一些數(shù)據(jù)

DataRow row0 = dt.Rows[0];

row0["Guid"] = Guid.NewGuid();

row0["EquRequestItemId"] = "";

row0["EquipmentType"] = "";

row0["Station"] = "";

row0["EquipmentNum"] = "1";//默認(rèn)初始為1

row0["EquipmentIds"] = "";

}

/// <summary>

/// 根據(jù)repeater相對(duì)應(yīng)的列名,定義數(shù)據(jù)源datatable的schema

/// </summary>

/// <param name="columns">列名</param>

/// <returns></returns>

public DataTable DefineDataTableSchema(string columns)

{

DataTable dt = new DataTable();

string[] columnsAry = columns.Split(',');

foreach (string str in columnsAry)

{

dt.Columns.Add(str);

}

return dt;

}

protected void rptRequest_ItemCommand(object source, RepeaterCommandEventArgs e)

{

if (e.CommandName == "add")

{

System.Web.UI.WebControls.Label lblGuid = (System.Web.UI.WebControls.Label)e.Item.FindControl("lblGuid");

//首先,恢復(fù)數(shù)據(jù)源

DataTable dt = DefineDataTableSchema(hfRptColumns.Value);

foreach (RepeaterItem item in rptRequest.Items)

{

DataRow newRow = dt.NewRow();

newRow["Guid"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text;

newRow["EquRequestItemId"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblEquRequestItemId")).Text;

newRow["EquipmentType"] = ((DropDownList)item.FindControl("ddlEquipmentType")).SelectedValue;

newRow["Station"] = ((DropDownList)item.FindControl("ddlStation")).SelectedValue;

newRow["EquipmentNum"] = ((TextBox)item.FindControl("txtReqEquipmentNum")).Text;

newRow["EquipmentIds"] = ((TextBox)item.FindControl("txtEquipmentIds")).Text;

dt.Rows.Add(newRow);

if (lblGuid.Text == ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text)

{

//添加一行

DataRow row = dt.NewRow();

row["Guid"] = Guid.NewGuid();

row["EquipmentType"] = "";

row["Station"] = "";

row["EquipmentNum"] = "1";//默認(rèn)初始為1

row["EquipmentIds"] = "";

dt.Rows.Add(row);

}

}

rptRequest.DataSource = dt;

rptRequest.DataBind();

}

else if (e.CommandName == "delete")

{

System.Web.UI.WebControls.Label lblGuid = (System.Web.UI.WebControls.Label)e.Item.FindControl("lblGuid");

//首先,恢復(fù)數(shù)據(jù)源

DataTable dt = DefineDataTableSchema(hfRptColumns.Value);

foreach (RepeaterItem item in rptRequest.Items)

{

if (lblGuid.Text != ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text)

{

DataRow newRow = dt.NewRow();

newRow["Guid"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblGuid")).Text;

newRow["EquRequestItemId"] = ((System.Web.UI.WebControls.Label)item.FindControl("lblEquRequestItemId")).Text;

newRow["EquipmentType"] = ((DropDownList)item.FindControl("ddlEquipmentType")).SelectedValue;

newRow["Station"] = ((DropDownList)item.FindControl("ddlStation")).SelectedValue;

newRow["EquipmentNum"] = ((TextBox)item.FindControl("txtReqEquipmentNum")).Text;

newRow["EquipmentIds"] = ((TextBox)item.FindControl("txtEquipmentIds")).Text;

dt.Rows.Add(newRow);

}

}

rptRequest.DataSource = dt;

rptRequest.DataBind();

}

}

protected void rptRequest_ItemDataBound(object sender, RepeaterItemEventArgs e)

{

if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)

{

DropDownList ddlEquipmentType_temp = e.Item.FindControl("ddlEquipmentType") as DropDownList;

string sqlstr = @"select distinct b.TypeId,b.EquipmentName + '_' + b.EquipmentType as 'EquipmentName_EquipmentType'

from EMS_EquipmentInfo a

join EMS_EquipmentType b on a.TypeId = b.TypeId and b.Status = '1'

order by EquipmentName_EquipmentType";

DataSet ds = DBUtility.DbHelperSQL.Query(sqlstr);

ddlEquipmentType_temp.DataTextField = "EquipmentName_EquipmentType";

ddlEquipmentType_temp.DataValueField = "TypeId";

ddlEquipmentType_temp.DataSource = ds;

ddlEquipmentType_temp.DataBind();

ddlEquipmentType_temp.SelectedValue = (e.Item.FindControl("lblEquipmentType") as System.Web.UI.WebControls.Label).Text;

DropDownList ddlStation_temp = e.Item.FindControl("ddlStation") as DropDownList;

string sqlstr2 = @"select NodeId,Line + '_' + StationName as 'Line_StationName' from V_Stations where status='1' order by Line_StationName";

DataSet ds2 = DBUtility.DbHelperSQL.Query(sqlstr2);

ddlStation_temp.DataTextField = "Line_StationName";

ddlStation_temp.DataValueField = "NodeId";

ddlStation_temp.DataSource = ds2;

ddlStation_temp.DataBind();

ddlStation_temp.SelectedValue = (e.Item.FindControl("lblStation") as System.Web.UI.WebControls.Label).Text;

TextBox txtEquIds = e.Item.FindControl("txtEquipmentIds") as TextBox;

txtEquIds.Attributes.Add("readonly", "true");

if (Request["BusinessNo"] != null)

{

(e.Item.FindControl("btnAddRow") as System.Web.UI.WebControls.Button).Visible = false;

(e.Item.FindControl("btnDeleteRow") as System.Web.UI.WebControls.Button).Visible = false;

string businessNo = Request["BusinessNo"].ToString();

bool IsApplyUser = Is_ApplyUser(Session["currentUserID"].ToString(), businessNo, "EMS_EquipmentRequest", "Requester");//是否為申請(qǐng)人本人

if (IsApplyUser == true)

{

string requestStatus = HttpUtility.UrlDecode(Request["RequestStatus"].ToString(), System.Text.Encoding.UTF8);//申請(qǐng)單的當(dāng)前狀態(tài)

if (requestStatus == "草稿" || requestStatus == "退回")

{

(e.Item.FindControl("btnAddRow") as System.Web.UI.WebControls.Button).Visible = true;

(e.Item.FindControl("btnDeleteRow") as System.Web.UI.WebControls.Button).Visible = true;

}

}

else

{

bool IsCurrentAppprovaler = Is_CurrentAppprovaler(Session["currentUserID"].ToString(), businessNo);//是否為當(dāng)前能做審批的人

if (IsCurrentAppprovaler == true)

{

string sql = " SELECT TOP 1 LayerName from EMS_Approvaler where BussinessNo='" + businessNo + "' "

+ " AND ApprovalStatus='N' ORDER BY AppSequence ";

DataTable dt = DBUtility.DbHelperSQL.Query(sql).Tables[0];

if (dt.Rows.Count != 0 && dt.Rows[0]["LayerName"].ToString() == "資產(chǎn)管理員")

{

string ReqNum = (e.Item.FindControl("txtReqEquipmentNum") as TextBox).Text.Trim();

txtEquIds.Attributes.Add("onclick", "OpenWindow('" + txtEquIds.ClientID + "','" + ddlEquipmentType_temp.SelectedValue + "','" + ReqNum + "')");

}

}

}

}

}

}

更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄

更多信息請(qǐng)查看網(wǎng)頁(yè)制作
易賢網(wǎng)手機(jī)網(wǎng)站地址:asp.net中Repeater控件用法筆記
由于各方面情況的不斷調(diào)整與變化,易賢網(wǎng)提供的所有考試信息和咨詢(xún)回復(fù)僅供參考,敬請(qǐng)考生以權(quán)威部門(mén)公布的正式信息和咨詢(xún)?yōu)闇?zhǔn)!
相關(guān)閱讀網(wǎng)頁(yè)制作

2025國(guó)考·省考課程試聽(tīng)報(bào)名

  • 報(bào)班類(lèi)型
  • 姓名
  • 手機(jī)號(hào)
  • 驗(yàn)證碼
關(guān)于我們 | 聯(lián)系我們 | 人才招聘 | 網(wǎng)站聲明 | 網(wǎng)站幫助 | 非正式的簡(jiǎn)要咨詢(xún) | 簡(jiǎn)要咨詢(xún)須知 | 加入群交流 | 手機(jī)站點(diǎn) | 投訴建議
工業(yè)和信息化部備案號(hào):滇ICP備2023014141號(hào)-1 云南省教育廳備案號(hào):云教ICP備0901021 滇公網(wǎng)安備53010202001879號(hào) 人力資源服務(wù)許可證:(云)人服證字(2023)第0102001523號(hào)
云南網(wǎng)警備案專(zhuān)用圖標(biāo)
聯(lián)系電話(huà):0871-65099533/13759567129 獲取招聘考試信息及咨詢(xún)關(guān)注公眾號(hào):hfpxwx
咨詢(xún)QQ:526150442(9:00—18:00)版權(quán)所有:易賢網(wǎng)
云南網(wǎng)警報(bào)警專(zhuān)用圖標(biāo)