取得datalist中所选取的项目的id值

首先添加datalist控件的onitemdatabound事件,并将其datakeyfield设置为你的数据库的主键。然后在linkbutton中添加自己的oncommand用法,并绑定commandArgument属性为你的数据库的主键,这样的目的是为了在后面的代码中取得所需要的主键值。

代码如下:

<asp:DataList runat="server" ID ="DataList1"
             Width="600px"
             DataKeyField="AID" onitemdatabound="DataList1_ItemDataBound">
 
        <itemtemplate>
 
                       <div align="right"> <asp:LinkButton ID="LinkButton1" runat="server" 

OnCommand ="reply"
                           CommandArgument ='<%#Eval("AID") %>'  >
                          回复留言
                        </asp:LinkButton>
                        <asp:LinkButton ID="LinkButton2" runat="server" OnCommand

="delete" CommandArgument ='<%#Eval("AID") %>'>
                          删除留言
                        </asp:LinkButton>  </div>   </itemtemplate>           
      </asp:DataList>

后台代码:
    protected void reply(object sender, CommandEventArgs e)
    {
        string id = e.CommandArgument.ToString();
        Response.Redirect("Reply.aspx?id="+id );
    }
    protected void delete(object sender, CommandEventArgs e)
    {
       string id= e.CommandArgument.ToString();
       if (Session["admin"] != null)
       {
           string sqlStr1 = "delete LiuYan where AID=" + id;
           Database db = new Database();
           if (db.ExecuteSql(sqlStr1))
           {
               Response.Write("<script language='javasript'>alert('删除成功!')</script>");
           }
           else
           {
               Response.Write("<script language='javasript'>alert('删除失败!')</script>");
           }
       }
       else
       {
           Response.Write("<script language='javasript'>alert('删除失败!没有管理权限,请先

登录!')</script>");
           Response.Redirect("Login.aspx");
       }
    }
    protected void DataList1_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        LinkButton dele = (LinkButton)e.Item.FindControl("LinkButton2");
        if (dele != null)
        {
            dele.Attributes.Add("Onclick ", "return confirm( '确定删除吗? ')");
        }
    }

posted @ 2009-08-30 16:18  Libo@Deng  阅读(1209)  评论(0编辑  收藏  举报