如何查找导致命令事件的数据项

本文关键字:命令 事件 数据项 何查找 查找 | 更新日期: 2023-09-27 18:07:46

我有nested-datalist和孩子datalist, itemcommand事件我正在做这样的事情

if (e.CommandName == "Delete")
{
    string keyID;
    int idx = e.Item.ItemIndex;
    DataClasses1DataContext db = new DataClasses1DataContext();
    DataList dl = Session["dl"] as DataList;
    object thisKey = dl.DataKeys[idx];
    keyID = thisKey.ToString();
    foreach (DataListItem item in dl.Items)
    {
        LinkButton lb = item.FindControl("LinkButton1") as LinkButton;
        ImageButton ib = item.FindControl("ImageButton1") as ImageButton;
        string s = item.ItemIndex.ToString();
        string j = s;
        if (item.ItemIndex == idx)
        {
           string dds = ib.AlternateText;
           Label ServiceCommentIDLabel = item.FindControl("ServiceCommentIDLabel") as Label;
           string ds = ServiceCommentIDLabel.Text;
           ServiceComment sc = db.ServiceComments.Where(o => o.ServiceCommentID == long.Parse(ServiceCommentIDLabel.Text)).First();
           db.ServiceComments.DeleteOnSubmit(sc);
           Response.Redirect("Services.aspx");
        }
     }
 }

它既没有选择精确的datakey也没有选择foreach循环遍历datalist的每个item

如何查找导致命令事件的数据项

你从Session得到DataList,这不是一件好事。您必须在ItemCommand事件中将DataList源从Object源转换为如下所示:

protected void Child_DataList_ItemCommand(object source, DataListCommandEventArgs e)
{
    if (e.CommandName == "Delete")
    {
        // get DataList from the source
        DataList dl = source as DataList;
        object thisKey = dl.DataKeys[e.Item.ItemIndex];
        // do your work here
    }
}