您的位置:首页 > 其它

Repeater数据控件的两个重要事件ItemDataBound 和 ItemCommand

2013-06-04 22:05 645 查看
1 ItemDataBound:数据绑定的时候(正在进行时)发生。

2 ItemCommand :用来响应Item模板中的控件的事件。

如下代码

aspx代码:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="LinqDataSource1"
onitemcommand="Repeater1_ItemCommand"
onitemdatabound="Repeater1_ItemDataBound">
<ItemTemplate>
<span runat="server" id="span">
--------------------<asp:Button ID="addButon" CommandName="addButton" CommandArgument='<%#Eval("part_code") %>' runat="server" Text="库存+1" />-------------------<%#Eval("part_code") %>---------------<%#Eval("stock_num") %><br/><br/>
</span>
</ItemTemplate>
</asp:Repeater>


cs代码:

//响应Item模板中控件的事件---------点击按钮,库存+1
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "addButton")//判断这个Item里哪个控件响应的这个事件
{
string part_code = (string)e.CommandArgument;//获取Item传过来的参数

//下面是通过Linq修改数据(即:使库存+1)
DataClasses1DataContext dc = new DataClasses1DataContext();
var rs = dc.tbl_stock_dtl.Select(r => r).Where(r => r.part_code == part_code);
if (rs.Count() > 0)
{
foreach (tbl_stock_dtl t in rs)
{
t.stock_num += 1;
}
}
dc.SubmitChanges();
Repeater1.DataBind();//强行刷新数据,就是说,库存+1后,立马显示新的数据。

}
}

//当浏览器显示一条记录的时候,响应的事件---------库存为零的背景变红
protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//判断Item的类型,因为Item有好几种:footer ,header ,Item....
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//把ItemData转换为对应的类对象
tbl_stock_dtl tsd = (tbl_stock_dtl)e.Item.DataItem;
if (tsd.stock_num == 0)
{
//找到对应的控件,因为span是html的,所以,要加上runat=“server”
HtmlGenericControl hgc = (HtmlGenericControl)e.Item.FindControl("span");

//为span动态添加一个属性:style,该属性的值为:background-color:red
hgc.Attributes.Add("style", "background-color:red");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐