如何获得Repeater中某行数据项的某列值。高手飘过~~~
其实‘Repeater中的每行数据就是一个对象,至于这个对象是什么类型,就要看你后台绑定的数据源了。我们通常是会绑定一张表(DataTable)的,那么这个对象的类型就是DataRowView类型了。
前台代码如下:
<div class="info details">
<h4>【站点详细信息】</h4>
<ul>
<asp:Repeater ID="rptStationDetailsInfo" runat="server"
onitemdatabound="rptStationDetailsInfo_ItemDataBound">
<ItemTemplate>
<li class="inner">站点编号:<%# Eval("stationId") %><>
<li class="inner">站点名称:<%# Eval("stationName")%><>
<li class="inner">是否启用:<%# Judge(Eval("inUse")) %><>
<li class="inner">所属分组:<%# Eval("groupName") %><>
<li class="inner">是否亮灯:<%# Judge(Eval("currentA")) %><>
<li class="inner">通讯信道名称:<%# Eval("channelName") %><>
<li class="inner">故障信息:<%# Judge(Eval("inError")) %><>
<li class="inner">安装时间:<%# Eval("installTime") %><>
<li class="inner">主板串号:<%# Eval("SerialNo") %><>
<li class="inner">软件版本:<%# Eval("softVersion") %><>
<li class="inner">SIM卡号:<%# Eval("SIMID") %><>
<li class="inner">固定IP:<%# Eval("RemoteIP")%><asp:Label ID="lblIP" runat="server"
Text="无" Visible = "false"></asp:Label><>
</ItemTemplate>
</asp:Repeater>
</ul>
</div>
我们后台绑定的代码如下:
if (!string.IsNullOrEmpty(stationId) && stationId != null) { StationInfoDAL stationInfo = new StationInfoDAL(); this.rptStationDetailsInfo.DataSource = new DataTable(); this.rptStationDetailsInfo.DataBind(); }
后台获取字段内容的代码如下:
protected void rptStationDetailsInfo_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.AlternatingItem||e.Item.ItemType==ListItemType.Item) { if (((DataRowView)e.Item.DataItem)["RemoteIP"]==null||((DataRowView)e.Item.DataItem)["RemoteIP"].ToString()=="") { Label label = (Label)e.Item.FindControl("lblIP"); label.Visible = true; } } }
这里请看我红色标注出来的部分,其实 (DataRowView) 是一个集合,我们要某列的值,只要用索引就可以得到了。
还有就是要注意我用下划线画出来的部分,这里很多人会漏写后面的判断,那是不可以的。具体什么原理,自己上网去看下。
上面说的情况是关于Repeater中的每个对象都是 (DataRowView) 类型的。
可是还有一些情况是我们后台绑定数据源的时候,不是把一张表作为数据源给Repeater.DataSource的。如下:
if (!string.IsNullOrEmpty(stationId) && stationId != null) { StationInfoDAL stationInfo = new StationInfoDAL(); this.rptStationDetailsInfo.DataSource = new List<Group>(); this.rptStationDetailsInfo.DataBind(); }
这样的情况下,我们的Repeater中的每个对象类型就是我们自己创建的类型Group了。
那么获取相应的字段代码就如下:
if (e.Item.ItemType == ListItemType.Item||e.Item.ItemType == ListItemType.AlternatingItem) { if ((bool)((Model.Group)e.Item.DataItem).bitSwitchOn) { Label label = (Label)e.Item.FindControl("lblSwitchOnInFact"); label.Visible = false; } if ((bool)((Model.Group)e.Item.DataItem).bitSwitchOff) { Label label = (Label)e.Item.FindControl("lblSwitchOffInFact"); label.Visible = false; } Repeater temp = (Repeater)e.Item.FindControl("rptSwitchShiftPoints"); temp.DataSource = autoRunShiftPts.GetEnabledSwitchPointsInfo(((Model.Group)e.Item.DataItem).autoRunId, ((Model.Group)e.Item.DataItem).groupId); temp.DataBind(); }
红色标注的地方就是获取相应的字段内容了,不过,与表获取不同的是,这里可以理解会获取对象中的成员。 bitSwitchOn 和 bitSwitchOff 是我创建的Model.Group下的两个属性成员