简体   繁体   中英

how to find datalist item which cause the command event

I am having nested-datalist and on child datalist , itemcommand event I am doing some thing like this

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

Neither its picking the exact datakey nor foreach loop traversing through each item of datalist .

You are getting DataList from Session which not good thing. You have to convert DataList from Object source in ItemCommand event like this:

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
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM