Access data from BoundField Gridview

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_Name" HeaderText="File Name" /> </Columns> <Columns> <asp:ButtonField ButtonType="Link" Text="Download" CommandName="DownloadFile" HeaderText="Download" /> </Columns> </asp:GridView> 

Now when I click the download button, how can I get the corresponding f_Id to get the related data from the database.

+1
source share
3 answers

This code should work, verified on my local computer.

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 open 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); } } 
+4
source

There are several ways to trick him, but you can access it as shown 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 } 

Then add f_id to the DataKeyNames attribute so that it retains the value of the hidden fields.

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

DataKeyNames

+2
source

The solution to your problem is described in this thread . Basically, you can access the row index in an event argument property called CommandArgument .

0
source

All Articles