现在的位置: 首页 > 综合 > 正文

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

2014年02月17日 ⁄ 综合 ⁄ 共 1581字 ⁄ 字号 评论关闭

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");
                }
            }
        }

【上篇】
【下篇】

抱歉!评论已关闭.