我们完成这样的一个任务:在Repeater数据控件中,点击模板中的按钮来递增数据值。比如这样:
点击上图中的按钮来递增文本框中的数据
代码如下:
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1"
onitemcommand="Repeater1_ItemCommand">
<ItemTemplate>
<span runat="Server" id="spanRow"><%#Eval("UserName") %>
<asp:TextBox runat="Server" ID="txtAge" Text='<%#Eval("Age")%>'>
</asp:TextBox></span>
<asp:Button runat="Server" CommandName="IncAge" CommandArgument='<%#Eval("Id") %>' Text="涨一岁" ID="txtAdd"/>
</ItemTemplate>
</asp:Repeater>
这是aspx前端的Repeater控件代码。可以看到利用了CommandName="IncAge" CommandArgument='<%#Eval("Id") %>'两个属性。再看看后台.cs代码:
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
if (e.CommandName == "IncAge")
{
long id = Convert.ToInt32(e.CommandArgument);
string str = "server=.; database=study; user id=sa; pwd=;";
SqlConnection con = new SqlConnection(str);
con.Open();
string Cmdstr = "update tb_RepeaterUser set Age=Age+1 where Id='"+id+"'";
SqlCommand cmd = new SqlCommand(Cmdstr,con);
cmd.ExecuteNonQuery();
this.Repeater1.DataBind();
con.Close();
}
}
在Repeater控件的ItemCommand事件中处理。递增完数据之后,记得重新绑定数据库,因为页面里的数据是之前的缓存里的数据内容,我们需要重新刷新数据库来重新绑定数据