I have a GridView like this
<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_Nam开发者_C百科e" HeaderText="File Name" />
</Columns>
<Columns>
<asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" />
</Columns>
</asp:GridView>
Now when I click on the download Button, how can I get the corresponding f_Id in order to get the related data from Database.
This code should work, tested on my local.
First, add DataKeyNames to your 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>
Then, access DataKeys from codebehind.
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);
}
}
A couple of ways to skin it, but you could access it like below:
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
}
And then add f_id, to the DataKeyNames attribute so it will store the hidden fields value.
<asp:GridView ID="gv_FilesList" runat="server" AutoGenerateColumns="false" onrowcommand="gv_FilesList_RowCommand" DataKeyNames="f_id">
DataKeyNames
A solution to your problem is described in this thread.
Basically you can access the row index in the event argument property called CommandArgument
.
精彩评论