2010-10-25 33 views
1

的綁定列訪問數據我有這樣從GridView的

<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand"> 
    <Columns> 
    <asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" /> 
    </Columns> 
    <Columns> 
    <asp:BoundField DataField="f_Name" HeaderText="File Name" /> 
    </Columns>          
    <Columns> 
    <asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" /> 
    </Columns> 
</asp:GridView> 

一個GridView現在,當我點擊下載按鈕,我怎麼能得到相應的F_ID爲了從數據庫中獲取相關數據。

回答

4

此代碼應工作,在我的本地測試。

首先,添加DataKeyNames到你的GridView。

<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_Id"> 
    <Columns> 
    <asp:BoundField DataField="f_Id" Visible="false" HeaderText="File Name" /> 
    </Columns> 
    <Columns> 
    <asp:BoundField DataField="f_Name" HeaderText="File Name" /> 
    </Columns>          
    <Columns> 
    <asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" /> 
    </Columns> 
</asp:GridView> 

然後,從代碼隱藏訪問DataKeys

protected void gv_FilesList_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "DownloadFile") 
    { 
     //row index 
     int index = Convert.ToInt32(e.CommandArgument); 

     //retrieve f_Id  
     int f_Id = Convert.ToInt32(gv_FilesList.DataKeys[index].Value); 

     //download file with f_Id 
     DownloadFile(f_Id); 
    } 
} 
+0

正是我需要的,它馬上就起作用! – Marcel 2013-04-10 08:05:47

0

一個解決問題的方法描述in this thread。 基本上,您可以訪問名爲CommandArgument的事件參數屬性中的行索引。

2

幾種方法剝皮,但你可以像下面訪問:

void gv_FilesList_RowCommand(Object sender, GridViewCommandEventArgs e) { 
    if(e.CommandName=="DownloadFile") 
    int index = Convert.ToInt32(e.CommandArgument); 
    GridViewRow row = gv_FilesList.Rows[index]; 
    string fileDownloadId = row.Cells[1].Text; 
    //Pull from DB 
} 

,然後添加F_ID,到的DataKeyNames屬性,因此將存儲隱藏字段的值。

<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_id"> 

DataKeyNames

+0

但是當我有Visible =「false」時,這是行不通的。我當然不想在gridview中顯示f_id。 – 2010-10-25 13:23:13

+0

更新您的gridview,並將f_id添加到上面的「DataKeyNames」屬性中。它是一個很好的小黑客,它會存儲隱藏的變量。 – Nix 2010-10-25 13:46:37