1. 这几天在做一个项目用到了Repeater,这个在网上说的可能不太多。因本人用到Repeater中绑定下拉列表实现方式如下。
在repeater上抓取控件及进行数据绑定大致分为两种:
(一种情况为:)
第一种在数据手动绑定后用for循环来查找下拉列表控件(其它控件原理一样)
代码如下:
前台代码大致为:
<asp:Repeater ID="rptList" runat="server" OnItemDataBound="rptList_ItemDataBound">
<HeaderTemplate>
<table width="100%" border="0" cellspacing="0" cellpadding="0" class="msgtable">
<tr>
.
.
.
<th width="12%" align="left">下拉列表</th>
.
.
.
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
.
.
.
<td><asp:DropDownList ID="ddlManager" runat="server" CssClass="select required"> </asp:DropDownList></td>
.
.
.
</tr>
</ItemTemplate>
</asp:Repeater>
后台代码:
private void DateBindView()
{
DataSet ds = 结果集合获得的方法,返回来的数据为DataSet类型。
// rptList为前台repeater的ID
rptList.DataSource = ds;
rptList.DataBind();
// 定义一个列表
DropDownList dllExample;
for (int j = 0; j < this.rptContent.Items.Count; j++)
{
dllExample= (DropDownList)this.rptContent.Items[j].FindControl("ddlManager");
dllExample.DataSource = BLL.StateInfoManager.GetList().Tables[0].DefaultView;
dllExample.DataTextField = "绑定的下拉列表名称";
dllExample.DataValueField = "绑定下拉列表的ID";
dllExample.DataBind();
DataRowView rowv = (DataRowView)this.rptContent.Items[j].DataItem;
//设置初始项
dllExample.Items.Add(new ListItem("-选择-", ""));
//获到当前列的状态ID用于绑定下拉列表
dllExample.SelectedValue = ds.Tables[0].Rows[j][绑定的下拉列表ID].ToString();
}
}
第一种方法就写完了。
第二种方法:
temDataBound方法中进行查找下拉列表,并进行当前数据的绑定.
前台还是如上:不过多了一个方法为:temDataBound 既: OnItemDataBound="rptList_ItemDataBound"
后台有所不同代码如下:
protected void rptList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
DropDownList dllExample= (DropDownList)e.Item.FindControl("ddlManager");
dllExample.DataTextField = "Remark";
dllExample.DataValueField = "stateid";
dllExample.DataSource = 获得的数据集合。(集合DATAset)
dllExample.DataBind();
dllExample.Items.Add(new ListItem("-Choose-", ""));
//找到分类Repeater关联的数据项
DataRowView rowv = (DataRowView)e.Item.DataItem;//获取当前项行数据再去访问那一列.注意坐标索引是从0开始
dllExample.SelectedValue =rowv[绑定的下拉列表ID列号].ToString();
}
}
希望对大家有所帮助。