展开全部
对于DataList,通常使用ItemCommand事件,请参考
.aspx
<asp:DataList ID="DataList1" runat="server"
onitemcommand="DataList1_ItemCommand">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Button ID="Button1" runat="server" CommandName="select" Text="选择"></asp:Button>
</ItemTemplate>
</asp:DataList>
<asp:Literal ID="lblMsg" runat="server"></asp:Literal>
.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
List<User> list = new List<User>();
list.Add(new User { Id = 1, Name = "aa" });
list.Add(new User { Id = 2, Name = "bb" });
list.Add(new User { Id = 3, Name = "cc" });
list.Add(new User { Id = 4, Name = "dd" });
DataList1.DataSource = list;
DataList1.DataKeyField = "Id";
DataList1.DataBind();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "select")
{
lblMsg.Text = (e.Item.FindControl("Label1") as Label).Text;
}
BindData();
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
.aspx
<asp:DataList ID="DataList1" runat="server"
onitemcommand="DataList1_ItemCommand">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Button ID="Button1" runat="server" CommandName="select" Text="选择"></asp:Button>
</ItemTemplate>
</asp:DataList>
<asp:Literal ID="lblMsg" runat="server"></asp:Literal>
.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
private void BindData()
{
List<User> list = new List<User>();
list.Add(new User { Id = 1, Name = "aa" });
list.Add(new User { Id = 2, Name = "bb" });
list.Add(new User { Id = 3, Name = "cc" });
list.Add(new User { Id = 4, Name = "dd" });
DataList1.DataSource = list;
DataList1.DataKeyField = "Id";
DataList1.DataBind();
}
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "select")
{
lblMsg.Text = (e.Item.FindControl("Label1") as Label).Text;
}
BindData();
}
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询