DataList控件,每笔记录会放置一个Button,让用户Click这个Button,将会获取这笔记录相关信息。下面这个例子演示是怎样获取记录的主键。
.aspx,你需要为Datalist写OnItemCreated事件和定义DataKwyField这样才可以定义记录铵钮事件与取得记录的主键值。
View Code
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DataList ID="DataList1" runat="server" DataKeyField="GalleryId"
OnItemCreated="DataList1_ItemCreated">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" />
</ItemTemplate>
</asp:DataList>
</ContentTemplate>
</asp:UpdatePanel>
.aspx.cs:
View Code
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Data_Binding();
}
}
private void Data_Binding()
{
this.DataList1.DataSource = xxx;
this.DataList1.DataBind();
}
protected void DataList1_ItemCreated(object sender, DataListItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
//判断Button是否存在
if (e.Item.FindControl("Button1") != null)
{
//如果存在,把对象转换为Button。
Button InsusButton = (Button)e.Item.FindControl("Button1");
//产生Button Click事件
InsusButton.Click += new EventHandler(InsusButton_Click);
}
}
}
private void InsusButton_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
DataListItem dli = (DataListItem)button.Parent;
string pk = this.DataList1.DataKeys[dli.ItemIndex].ToString();
//下面Utility请从Insus.NET博客下载
(new InsusJsUtility()).JsAlert(pk);
}