如何从datalist中的datakey字段获取值

时间:2012-11-02 12:32:41

标签: c# asp.net

我有一个datalist,我设置了DataKeyField

 <asp:DataList ID="lstItems" runat="server" RepeatDirection="Horizontal"  DataKeyField="itemid" >
  <ItemTemplate>
  //contents in the datalist here
  </ItemTemplate>
   </asp:DataList> 

我在页面中也有一个图像按钮说imgADD。我的问题是如何在imgADD中获取datakey的值点击服务器端

2 个答案:

答案 0 :(得分:4)

<asp:DataList ID="DataList_projects" runat="server" RepeatColumns="1" DataKeyNames="ID"
         RepeatDirection="Horizontal" onitemcommand="DataList_projects_ItemCommand" >

        <HeaderStyle ForeColor="Red" />
    <ItemTemplate>
        <hr style="color:" />
     <asp:Label ID="ltlproject" ForeColor="#cc0000"  runat="server" text="PROJECT:"></asp:Label>  &nbsp;<b><u><asp:Label ID="lblProject" runat="server" Text='<%# Eval("TITLE")%>' ></asp:Label></u></b> &nbsp;  <asp:LinkButton ID="lnkEdit" ForeColor="Red"  CommandName="Edit" runat="server">Edit</asp:LinkButton><br />


    </ItemTemplate>
    </asp:DataList>

中的代码

protected void DataList_projects_ItemCommand(object source, DataListCommandEventArgs e)
    {

        if (e.CommandName == "Edit")
        {

           string strId = DataList_projects.DataKeys[e.Item.ItemIndex].ToString();

        }

    }

我认为这会对你有帮助....

答案 1 :(得分:0)

ASPX代码:

//In the DataList ItemTemplate: 
.. 
.. 
<asp:ImageButton ID="imgADD" runat="server" ImageUrl="uri" ToolTip="Add" 
CommandName="Add" />

代码隐藏:

protected void DataList1_ItemCommand(object source, 
DataListCommandEventArgs e) 
{ 
  if(e.CommandName == "Add") 
  { 
    string keyID; 

    // Get the index of the row from which this event was raised. 
    int idx = e.Item.ItemIndex; 

    // Get the DataKey with the same index. 
    object thisKey = DataList1.DataKeys(idx); 
    if(thisKey != null) 
    { 
      keyID = thisKey.ToString(); 
      // do something here 
    } 
 } 

}