ASP.NET 데이터 바 인 딩 작업 중 Repeater 컨트롤 의 용법 을 자세히 알 아 봅 니 다.
1.귀속 컨트롤 의 Repeater
.NET 은 GridView,DataList 등 다양한 데이터 바 인 딩 컨트롤 을 패키지 합 니 다.그러나 이 글 은 Repeater 에서 시작 합 니 다.Repeater 는 기본 적 인 데이터 바 인 딩 템 플 릿 만 제공 하고 다른 페이지 등 기능 이 내장 되 어 있 지 않 기 때문에 가장 원시 적 인 데이터 바 인 딩 컨트롤 입 니 다.Repeater 컨트롤 의 다른 바 인 딩 컨트롤 을 능숙 하 게 활용 하면 간단 합 니 다.
1.Repeater 안내
Repeater 컨트롤 은 기본 템 플 릿 화 된 데이터 목록 입 니 다.GridView 컨트롤 처럼 시각 화 된 디자인 형식 이나 스타일 이 아 닙 니 다.따라서 개발 할 때 컨트롤 템 플 릿 에 모든 형식,형식,스타일 표 시 를 명시 해 야 합 니 다.또한 Repeater 컨트롤 은 선택,정렬,편집,페이지 나 누 기 등 기능 이 내장 되 어 있 지 않 으 며 기본 데이터 바 인 딩 만 제공 하지만 개발 자 에 게 ItemCommand 이 벤트 를 제공 합 니 다.이 이 벤트 는 컨트롤 에서 수신 명령 을 지원 합 니 다.
데 이 터 를 연결 하려 면 템 플 릿 이 없어 서 는 안 됩 니 다.Repeater 컨트롤 은 데이터 템 플 릿 을 지원 하고 템 플 릿 에 원 하 는 탭 을 추가 할 수 있 습 니 다.다음 그림 과 같은 주요 용법 입 니 다.
Note:모든 Repeater 컨트롤 은 ItemTemplate 를 정의 해 야 합 니 다.
2.컨트롤 사용 방법
위의 글 은 Repeater 의 기본 적 인 사용 방법 과 그 기본 적 인 특성 을 설명 하 였 으 며,다음 에 몇 가지 전형 적 인 예 를 들 어 Repeater 컨트롤 을 활용 하 였 다.
1.데이터 바 인 딩 의 삭제,편집
이 예제 에 서 는 Asp.net 의 프론트 데스크 톱 과 백 스테이지 결합 을 사용 하여 데 이 터 를 표시 하고 데 이 터 를 편집 하고 삭제 할 수 있 습 니 다.
페이지 삭제:
페이지 편집:
프론트 코드:편집 단 추 를 누 르 면 편집 페이지 에 들 어 갑 니 다.페이지 는 두 개의 Panel 컨트롤 로 제 어 됩 니 다.ID 번 호 를 전달 하 는 방식 으로 페이지 를 편집 할 지 삭제 할 지 판단 합 니 다.또한 프론트 코드 는 컨트롤 의 CommandArgument 속성 을 설정 하여 배경 에서 판단 해 야 할 id 번 호 를 전달 합 니 다.
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="userRepeat" runat="server" OnItemCommand="userRepeat_ItemCommand" OnItemDataBound="userRepeat_ItemDataBound">
<HeaderTemplate>
<table border="1" style="width:1000px;text-align:center;border-collapse:collapse;">
<thead style="background-color:red;">
<tr>
<th>ID</th>
<th> </th>
<th> </th>
</tr>
</thead>
</HeaderTemplate>
<ItemTemplate>
<asp:Panel ID="plItem" runat="server">
<tr>
<td><asp:Label runat="server" ID="lblID" Text='<%#Eval("id") %>'></asp:Label></td>
<td><%#Eval("name") %></td>
<td>
<asp:LinkButton ID="lbtEdit" CommandName="Edit" CommandArgument='<%#Eval("id") %>' runat="server"> </asp:LinkButton>
<asp:LinkButton ID="lbtDelete" CommandName="Delete" CommandArgument='<%#Eval("id") %>' runat="server"> </asp:LinkButton>
</td>
</tr>
</asp:Panel>
<asp:Panel ID="plEdit" runat="server">
<tr>
<td><asp:Label runat="server" ID="Label1" Text='<%#Eval("id") %>'></asp:Label></td>
<td><asp:TextBox ID="txtName" runat="server" Text='<%#Eval("name") %>'></asp:TextBox></td>
<td>
<asp:LinkButton ID="lbtCancel" CommandName="Cancel" CommandArgument='<%#Eval("id") %>' runat="server"> </asp:LinkButton>
<asp:LinkButton ID="lbtUpdate" CommandName="Update" CommandArgument='<%#Eval("id") %>' runat="server"> </asp:LinkButton>
</td>
</tr>
</asp:Panel>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
</form>
</body>
백 엔 드 코드:백 엔 드 코드 에서 중요 한 두 사건 은 ItemCommand 와 ItemDataBound 입 니 다.그 중에서 ItemCommand 는 프론트 에서 들 어 오 는 단추 명령 을 받 고 명령 의 매개 변수 에 따라 백 엔 드 에서 전달 하 는 id 를 설정 하 며 ItemDataBound 에서 id 판단 전환 디 스 플레이 Panel 을 검증 합 니 다.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class EditPage : System.Web.UI.Page
{
private int id = 0; // ID
/// <summary>
///
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.DataBindToRepeater();// Repeater
}
}
/// <summary>
/// Repeater
/// </summary>
private void DataBindToRepeater() {
// using
using (SqlConnection sqlCon=new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
{
sqlCon.Open(); //
SqlCommand sqlcom = new SqlCommand(); //
sqlcom.CommandText = "select * from match"; //
sqlcom.Connection = sqlCon; //
this.userRepeat.DataSource = sqlcom.ExecuteReader(); // Repeater
this.userRepeat.DataBind(); //
}
}
/// <summary>
/// Repeater
/// </summary>
/// <param name="source"></param>
/// <param name="e"></param>
protected void userRepeat_ItemCommand(object source, RepeaterCommandEventArgs e)
{
// , ,
if (e.CommandName=="Edit") //
{
id = int.Parse(e.CommandArgument.ToString()); // ID
}
else if (e.CommandName=="Cancel") //
{
id = -1;
}
else if(e.CommandName=="Delete") //
{
id = int.Parse(e.CommandArgument.ToString()); // ID
// ,
this.DeleteRepeater(id);
}
else if (e.CommandName == "Update") //
{
// ID
string strText = ((TextBox)e.Item.FindControl("txtName")).Text.Trim();
int intId=int.Parse(((Label)e.Item.FindControl("lblID")).Text);
// Repeater
this.UpdateRepeater(strText,intId);
}
//
this.DataBindToRepeater();
}
/// <summary>
///
/// </summary>
/// <param name="intId"> ID</param>
private void DeleteRepeater(int intId) {
using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
{
sqlCon.Open(); //
SqlCommand sqlcom = new SqlCommand(); //
sqlcom.CommandText = "delete from match where id=@id"; //
sqlcom.Connection = sqlCon; //
// , sqlcom
SqlParameter sqlParam = new SqlParameter("@id", intId);
sqlcom.Parameters.Add(sqlParam);
sqlcom.ExecuteNonQuery(); //
}
}
/// <summary>
/// Repeater
/// </summary>
/// <param name="strText"> </param>
/// <param name="intId"> ID </param>
private void UpdateRepeater(string strText,int intId) {
using (SqlConnection sqlCon = new SqlConnection("server=.;database=MyBlog;uid=sa;pwd=1"))
{
sqlCon.Open(); //
SqlCommand sqlcom = new SqlCommand(); //
sqlcom.CommandText = "update match set name=@str where id=@id"; //
sqlcom.Connection = sqlCon; //
// , sqlcom
SqlParameter[] sqlParam = { new SqlParameter("@str", strText), new SqlParameter("@id", intId) };
sqlcom.Parameters.AddRange(sqlParam);
sqlcom.ExecuteNonQuery(); //
}
}
/// <summary>
/// Repeater
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void userRepeat_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
// Repeater ,
//ListItemType , DataGrid、 DataList Repeater 。
if (e.Item.ItemType==ListItemType.Item || e.Item.ItemType==ListItemType.AlternatingItem)
{
// , sqlReader , DbDataRecord
// DataTable .
System.Data.Common.DbDataRecord record = (System.Data.Common.DbDataRecord)e.Item.DataItem;
//DataTable
//System.Data.DataRowView record = (DataRowView)e.Item.DataItem;
// id id, userRepeat_ItemCommand
if (id == int.Parse(record["id"].ToString()))
{
((Panel)e.Item.FindControl("plItem")).Visible = false;
((Panel)e.Item.FindControl("plEdit")).Visible = true;
}
else
{
((Panel)e.Item.FindControl("plItem")).Visible = true;
((Panel)e.Item.FindControl("plEdit")).Visible = false;
}
}
}
}
}
2.페이지--PageDataSource프론트 코드:원본 html 텍스트 를 사용 하고 Literal 탭 을 추가 하여 html 탭 을 동적 으로 추가 하고 지정 합 니 다.
페이지 캡 처:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<style type="text/css">
.pageBar
{
margin-top: 10px;
}
.pageBar a
{
color: #333;
font-size: 12px;
margin-right: 10px;
padding: 4px;
border: 1px solid #ccc;
text-decoration: none;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Repeater ID="Repeater1" runat="server" >
<HeaderTemplate>
<table border="1" cellpadding="0" cellspacing="0" style="width:1006px;border-collapse:collapse; text-align:center;">
<tr>
<th style="background-color:red">ID</th>
<th style="background-color:red"> </th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td><asp:Label ID="lblId" runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"id") %>' ></asp:Label></td>
<td><%# DataBinder.Eval(Container.DataItem,"name") %></td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
</div>
<div class="pageBar">
<asp:Literal ID="ltlPageBar" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
백 엔 드 코드:Repeater 컨트롤의 데이터 원본 은 PagedDataSource 대상 입 니 다.페이지 를 불 러 올 때 이 대상 에 게 페이지 의 속성 을 동적 으로 지정 하고 Literal 탭 을 사용 하여 탭 마다 페이지 를 넘 기 는 링크 를 동적 으로 지정 합 니 다.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication4
{
public partial class PageDemo : System.Web.UI.Page
{
private string id = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//
int pageIndex = 1;
try
{
//
pageIndex = Convert.ToInt32(Request.QueryString["Page"]);
// 0 1
if (pageIndex <= 0)
{
pageIndex = 1;
}
}
catch
{
pageIndex = 1;
}
DataTable dt = this.GetDataTable(); //
PagedDataSource pds = new PagedDataSource(); //
pds.DataSource = dt.DefaultView; //
pds.AllowPaging = true; //
pds.PageSize = 2; //
pds.CurrentPageIndex = pageIndex - 1; //
// Repeater
this.Repeater1.DataSource = pds;
this.Repeater1.DataBind();
// Literal
ltlPageBar.Text = this.GetPageBar(pds);
}
}
/// <summary>
///
/// </summary>
/// <param name="pds"> </param>
/// <returns> html </returns>
private string GetPageBar(PagedDataSource pds)
{
string pageBar = string.Empty; //
int currentPageIndex = pds.CurrentPageIndex + 1; //
//
if (currentPageIndex == 1) // ,
{
pageBar += "<a href=\"javascript:void(0)\"> </a>";
}
else
{
// , 1
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=1\"> </a>";
}
//
if ((currentPageIndex - 1) < 1) // 1
{
pageBar += "<a href=\"javascript:void(0)\"> </a>";
}
else
{
// 1
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex - 1) + "\"> </a>";
}
//
if ((currentPageIndex + 1) > pds.PageCount)
{
// ,
pageBar += "<a href=\"javascript:void(0)\"> </a>";
}
else
{
//
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + (currentPageIndex + 1) + "\"> </a>";
}
//
if (currentPageIndex == pds.PageCount)
{
pageBar += "<a href=\"javascript:void(0)\"> </a>";
}
else
{
pageBar += "<a href=\"" + Request.CurrentExecutionFilePath + "?Page=" + pds.PageCount + "\"> </a>";
}
return pageBar; // html
}
/// <summary>
/// ,
/// </summary>
/// <returns>DataTable, </returns>
private DataTable GetDataTable()
{
DataTable dt = new DataTable(); //
using (SqlConnection con = new SqlConnection("server=.;DataBase=MyBlog;uid=sa;pwd=1;"))
{
con.Open(); //
SqlCommand sqlCom = new SqlCommand(); //
StringBuilder sqlStr = new StringBuilder(); // sql
sqlStr.Append("select * from match"); // sql
sqlCom.CommandText = sqlStr.ToString(); // sqlcommand sql
sqlCom.Connection = con; // sqlcommand
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCom); //
SqlCommandBuilder sqlBuilder = new SqlCommandBuilder(sqlDa);
sqlDa.Fill(dt); //
}
return dt;
}
}
}
결어이 글 은 리 피 터 컨트롤 의 기본 적 인 사용 방법 을 소개 하고 두 가지 예 시 를 통 해 리 피 터 컨트롤 의 사용 을 더욱 깊이 배 웠 다.Repeater 컨트롤 은 패키지 작업 이 적 지만 가장 기본 적 인 데이터 바 인 딩 컨트롤 입 니 다.또한 다른 컨트롤 을 사용 하여 Repeater 컨트롤 의 부족 을 보완 할 수 있 습 니 다.예 를 들 어 PagedataSource 류 를 사용 하여 데이터 의 페이지 를 나 눌 수 있 습 니 다.글 은 여기까지 쓰 고 끝나 지 않 았 습 니 다.다음 글 은 ListView 에 중심 을 두 고 토론 할 것 입 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
부트스트랩 ASP.NET에서 설정하는 법1) _Layout.cshtml 內 link로 bootstrap 참조 2) Nuget 패키지에서 BootStrap 다운로드 3) 하단 부트스트랩 예제 사이트 참고해서 프로젝트 개발 참고 :...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.